# Python - Introduction

Published:

This post covers Introduction to Python Programming.

# Hello Python!

• Assignment Operator, =

• No need to declare before assignment
• Function call - print()

• Comment - single line comment or triple-quoted string literals

• if statement

• string - single quote or double quote

• type

• Addition, Subtraction, Multiplication, True Division (/); Floor Division (//); Modulus (%); Exponentiation (**); Negation

• Order - Parentheses, Exponents, Multiplication/Division, Addition/Subtraction

• Built-in Functions: min, max, abs, float, int

• help() function e.g. help(min)

• Defining Function

• Docstring - triple quoted string for help()
• return is optional (if no return then python return None): ret = print()
• default arguments
• Function applied to Function - Higher Order Function

• def pow2(x):
return x*x

def call_pow2(fn, arg):
val = fn(arg)
return val

print(pow2(3))  # 9
print(call_pow2(pow2, 6))  # 36

def pow4(fn, arg):
val = fn(arg)
val = fn(val)
return val

print(pow4(pow2, 2)) # 16

• # Which number is biggest modulo 5
print(max(120, 102, 104)) # 120

def mod5(x):
return x % 5

print(max(120, 102, 104, key=mod5)) # 104

• Data Type: bool

• # True or False
# compbine: and or not
3.0 == 3 # True
'3' == 3 # False
# if elif else
bool(1) # True for all numbers except 0
bool(0) # False

bool('abc') # True for all strings/other types except empty
bool('') # False
x = 5
if x:
print('Greater than zero or non-empty string')
else:
print('equal to zero or empty string')

• Lists

• Ordered sequence of values

• nums = [2, 4, 6, 8]

nums = [[1, 3, 5, 7], [2, 4, 6, 8]]

nums = [[1, 3, 5, 7],
[2, 4, 6, 8]]

nums = [[1, 3, 5, 7],
[2, 4, 6, 8],]

nums = [['1', 3, 5, '7'],
[2, '4', '6', 8]]

# Indexing
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
nums[0], nums[-1]

# Slicing
num[1:5], num[3:], nums[-3:]

# List are mutable (can be modifiied in place)
nums = [1, 3, 5, 7, 9]
nums[-2:] = [11, 13, 15] # [1, 3, 5, 11, 13, 15]

# List functions
len(), sum(), sorted(), min(), max()

• Objects

• Everything in python is an object

• Object carry somethings (attributes and methods) around with them and can be accessed using dot

• num = 5
print(num.imag) # 0

num = 5 +2j
print(num) # (5+2j)
print(num.imag) # 2.0

num = 100
print(num.bit_length()) # only for int



# List Methods: append, pop, search(index), in

nums = [1, 3, 5, 7] nums.append(9) help(nums.append)

nums.pop()

nums.index(5)

9 in nums

help(nums) # see all methods for nums 

• Tuples

• t = (1, 2, 3)

# Immutable
t[0] = 10 # Error

# Used to return multiple values
num = 0.25
num.as_integer_ratio() # return tuple (1, 4)

# Swap values
a = 2
b = 5
a, b = b, a

• Loops

• planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

for planet in planets:
print(planet, end=' ')

print()
for idx in range(len(planets)):
print(planets[idx], end=' ')

print()
i = 0
while i <= 7:
print(planets[i], end=' ')
i += 1

• List Comprehensions

• planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

lengths = [planet for planet in planets if len(planet) < 6]
print(lengths)

lengths = [planet if len(planet) < 6 else 'None' for planet in planets]
print(lengths)

• Strings

• hello = "hello\nworld"
print(hello)

print()
hello = """hello

world"""
print(hello)

# Strings are sequence and can be sliced
hello[0], hello[-5:]

# String is Immutable
hello[0] = 'H' # error

• # String Methods
hello = "hello world"
hello.upper()
hello.lower()
hello.index('world')
hello.startswith('hello')
hello.endswith('world')
words = hello.split()
hello = " ".join(words)

datestr = '2021-01-11'
year, month, day = datestr.split('-')
'/'.join([year, month, day])

date = f'{year}/{month}/{day}'

• Dictionary

• planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
p2i = {planets[idx]:idx for idx in range(len(planets))}
i2p = { v:k for k,v in p2i.items()}

• External Libraries

• import math
print(type(math))
print(dir(math))
print(math.pi)
print(math.log(8, 2))
print(help(math.log))
print(help(math))

import math as mt
print(mt.pi)

from math import pi, log
print(pi)
print(log(8, 2))

• import numpy
print(type(numpy))
print(type(numpy.random))
print(dir(numpy.random))

rolls = numpy.random.randint(low=1, high=6, size=10)
print(rolls)

print(type(rolls)) # What is this
print(dir(rolls)) # What can be done with it

print(rolls.mean())
print(rolls.tolist())

• # Opertaor Overloading - depends on the library
# [1, ,2, 3, 4] + 5 # Error in the list

import numpy as np
np.array([1, 2, 3, 4]) + 5 # works fine in array

print(np.array([1, 2, 3, 4, 5]) <= 3)

list_ = [[1, 2, 3], [4, 5, 6]]
list_ = np.array(list_)
print(list_)
print(list_[1, -1])
`

Tags: