type()
To get the type of any object use type().
x = 4
print(type(x))
Multiple Assignment and Swapping Variables
a, b, c = 15, 16, 17 a, b = b, a
Variables and parameters are local
Variables and parameters inside a function exist only inside that function.
Modules
A module is a file containing python commands such as the math module or one created by yourself.
import math
Expressions and Statements
- Expression — combination of values and operations that create a new value (return a value)
- Statement — performs a task with no return value e.g. controlling the flow of the program
Expressions can be printed whereas statements cannot.
x+5 #expression y=x+5 #statement
Recursion
Recursion is when a function calls itself, e.g.
def countdown(n): if n <= 0: print(' Blastoff!' ) else: print(n) countdown(n-1)
Infinite recursion is generally not a good idea
def recurse(): recurse()
Python will report an error message when the maximum recursion depth is reached:
>>>RuntimeError: Maximum recursion depth exceeded
Errors in Assuming Equality (Floating Point)
In math (a + b) + c is equal to a + (b + c).
In python the following will return false due to the rounding off of floating point calculations.
a = 11111113 b = -11111111 c = 7.51111111 (a + b) + c == a + (b + c)
With floating point numbers equality is better tested with closeness rather than absolute equality.
x = (a + b) + c y = a + (b + c) x == y #returns False abs(x-y) < 0.0000001 #returns True
‘==’ vs ‘is’
‘==’ is used to check equality of value
‘is’ is used to check if two names refer to the same object (same ID)
a = 2.5 b = 2.5 c = b #c and b same object and ID a == b #returns True a is b #returns False, objects are different c is b #returns True, same object id(a) #921 id(b) #923 id(c) #923
Range
range(start, end, step)
If only one value is included, it will be the end value (which is never included).
range(5) #0, 1, 2, 3, 4 range(3, 10) #3, 4, 5, 6, 7, 8, 9 range(1, 20, 4) #1, 5, 9, 13, 17
Range is it’s own type.
list vs tuple
keywords vs built-in functions
f strings