a = [1,0,2,1] # Input list
a.sort() # Sort list, note in-place modification
a
[0, 1, 1, 2]
n = len(a) # Calculate length of list 'a'
n
4
m = (n + 1)//2 # Calculate mid-point, // is operator for integer division
m
2
n % 2 == 1 # Check whether the number of elements is odd, % (modulo) gives remainder of division
False
sum(a[m-1:m+1])/2 # Calculate median, as the mean of the two numbers around the mid-point
1.0
if
)while
)len()
)TypeError
)if
¶if
- defines condition under which some code is executedif <boolean_expression>:
<some_code>
a = [1,0,2,1,100] # Note that addion of a large value (100) had no effect on the median here
a.sort()
n = len(a)
m = (n + 1)//2
if n % 2 == 1:
print(a[m-1])
1
if - else
¶if - else
- defines both condition under which some code is executed and alternative code to executeif <boolean_expression>:
<some_code>
else:
<some_other_code>
a = [1,0,2,1]
a.sort()
n = len(a)
m = (n + 1)//2
if n % 2 == 1:
print(a[m-1])
else:
print(sum(a[m-1:m+1])/2)
1.0
if - elif - ... - else
¶if - elif - ... - else
- defines both condition under which some code is executed and several alternativesif <boolean_expression>:
<some_code>
elif <boolean_expression>:
<some_other_code>
...
...
else:
<some_more_code>
x = 42
if x > 0:
print('Positive')
elif x < 0:
print('Negative')
else:
print('Zero')
Positive
num = float(input('Please, enter a number:')) # Ask for user input and cast as float
if num % 2 == 0:
print('Even')
elif num % 2 == 1:
print('Odd')
else:
print('This is a real number')
Please, enter a number:43 Odd
num = int(input('Please, enter a number:')) # Ask for user input and cast as integer
if num > 0:
if num % 2 == 0:
print('Positive even')
else:
print('Positive odd')
elif num < 0:
if num % 2 == 0:
print('Negative even') # Notice that odd/even checking appears twice,
else:
print('Negative odd') # Consider abstracting this as a function
else:
print('Zero')
Please, enter a number:-43 Negative odd
x = -43
if x % 2 == 0:
print('Even')
if x > 0:
print('Positive')
else:
print('Negative')
x = -43
if x % 2 == 0:
print('Even')
if x > 0:
print('Positive')
else:
print('Negative')
Negative
<expr1> if <test> else <expr2>
x = 42
y = 'even' if x % 2 == 0 else 'odd'
y
'even'
while
¶while
- defines a condition under which some code (loop body) is executed repeatedlywhile <boolean_expression>:
<some_code>
# Calculate a factorial with decrementing function
# E.g. 5! = 1 * 2 * 3 * 4 * 5 = 120
x = 5
factorial = 1
while x > 0:
factorial *= x # factorial = factorial * x
x -= 1 # x = x - 1
factorial
120
for
¶for
- defines elements and sequence over which some code is executed iterativelyfor <element> in <sequence>:
<some_code>
x = range(1,6)
factorial = 1
for i in x:
factorial *= i
factorial
120
# Find maximum value in a list with exhaustive enumeration
l = [3, 27, 9, 42, 10, 2, 5]
max_val = l[0]
for i in l:
if i > max_val:
max_val = i
max_val
42
range()
function¶range()
function generates arithmetic progressions and is essential in for
loopsrange(start, stop[, step])
start
and stop
are 0 and 1print(range(3))
print(list(range(3)))
range(0, 3) [0, 1, 2]
range()
function in for
loops¶l = [3, 27, 9, 42, 10, 2, 5]
for i in range(len(l)):
print(l[i], end = ' ')
3 27 9 42 10 2 5
l = [3, 27, 9, 42, 10, 2, 5]
s = []
for i in range(1, len(l), 2):
s.append(str(l[i]))
s
['27', '42', '2']
__iter__
method, which return iteratorrange()
)zip()
function provides a convenient way of iterating over several sequences simultaneouslyl = [3, 27, 9, 42]
s = ['three', 'twenty seven', 'nine', 'forty-two']
for i, j in zip(l, s):
print(str(i) + ' - ' + j)
3 - three 27 - twenty seven 9 - nine 42 - forty-two
items()
method allows to iterate over keys and values in a dictionaryd = {'apple': 150.0, 'banana': 120.0, 'watermelon': 3000.0}
for k, v in d.items():
print(k.upper(), int(v))
APPLE 150 BANANA 120 WATERMELON 3000
break
and continue
¶break
- terminates the loop in which it is containedcontinue
- exits the iteration of a loop in which it is containedfor i in range(1,6):
if i % 2 == 0:
break
print(i)
1
for i in range(1,6):
if i % 2 == 0:
continue
print(i)
1 3 5
break
statement (or Ctrl/Cmd-C in interactive session)i = 1
while True:
i += 1
if i > 10:
break
i
11
[<expr> for <elem> in <iterable>]
[<expr> for <elem> in <iterable> if <test>]
[<expr> for <elem1> in <iterable1> for <elem2> in <iterable2>]
l = [0, 'one', 1, 2]
[x * 2 for x in l]
[0, 'oneone', 2, 4]
[x * 2 for x in l if type(x) == int]
[0, 2, 4]
[x.upper() for x in l if type(x) == str]
['ONE']
{<expr> for <elem> in <iterable> if <test>}
{<key>: <value> for <elem1>, <elem2> in <iterable> if <test>}
o = {'apple', 'banana', 'watermelon'}
{e[0].title() + ' - ' + e for e in o}
{'A - apple', 'B - banana', 'W - watermelon'}
d = {'apple': 150.0, 'banana': 120.0, 'watermelon': 3000.0}
{k.upper(): int(v) for k, v in d.items()}
{'APPLE': 150, 'BANANA': 120, 'WATERMELON': 3000}
break
and continue
to shorten iterationslen()
, range()
, zip()
def <function_name>(arg_1, arg_2, ..., arg_n):
<function_body>
def foo(arg):
pass # does nothing, but is required as 'def' statement cannot be empty
def
statementhelp()
)def calculate_median(lst):
"""Calculates median
Takes list as input
Assumes all elements of list are numeric
"""
lst.sort()
n = len(lst)
m = (n + 1)//2
if n % 2 == 1:
median = lst[m-1]
else:
median = sum(lst[m-1:m+1])/2
return median
<function_name>(arg_1, arg_2, ...)
a = [1, 0, 2, 1]
calculate_median(a)
1.0
calculate_mean(a)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Input In [35], in <cell line: 1>() ----> 1 calculate_mean(a) NameError: name 'calculate_mean' is not defined
return
statement is encounteredreturn
None
if no return
statementdef is_positive(num):
if num > 0:
return True
elif num < 0:
return False
res1 = is_positive(5)
res2 = is_positive(-7)
res3 = is_positive(0)
print(res1)
print(res2)
print(res3)
True False None
def format_date(day, month, year, reverse = True):
if reverse:
return str(year) + '-' + str(month) + '-' + str(day)
else:
return str(day) + '-' + str(month) + '-' + str(year)
format_date(4, 10, 2021)
'2021-10-4'
format_date(day = 4, month = 10, year = 2021)
'2021-10-4'
format_date(4, 10, 2021, False)
'4-10-2021'
format_date(day = 4, month = 10, year = 2021, False)
Input In [42] format_date(day = 4, month = 10, year = 2021, False) ^ SyntaxError: positional argument follows keyword argument
*
in function definition collects unmatched position arguments into a tuple**
collects keyword arguments into a dictionarydef foo(*args):
print(args)
foo(1, 'x', [5,6,10])
(1, 'x', [5, 6, 10])
def foo(**kwargs):
print(kwargs)
foo(first = 1, second = 'x', third = [5,6,10])
{'first': 1, 'second': 'x', 'third': [5, 6, 10]}
def <function_name>(arg_1, ..., arg_n, *args, kwarg_1, ..., kwarg_n, **kwargs):
<function_body>
def foo(a, b, *args, c = False, **kwargs):
print(a, b, args, c, kwargs)
foo(1, 'x', 20, 'cat', c = True, last = [10, 99])
1 x (20, 'cat') True {'last': [10, 99]}
def which_integer(num):
def even_or_odd(num):
if num % 2 == 0:
return 'even'
else:
return 'odd'
if num > 0:
eo = even_or_odd(num)
return 'positive ' + eo
elif num < 0:
eo = even_or_odd(num)
return 'negative ' + eo
else:
return 'zero'
which_integer(-43)
'negative odd'
even_or_odd(-43)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Input In [51], in <cell line: 1>() ----> 1 even_or_odd(-43) NameError: name 'even_or_odd' is not defined
x = 5
def foo():
x = 12
return x
y = foo()
print(y)
print(x)
12 5
local
to the function, if a variable is assigned inside def
nonlocal
to nested function, if a variable is assigned in an enclosing def
global
to the file (module), when a variable is assigned outside all def
sLEGB rule |
Source: Mark Lutz |
def
statement, it is possible to generate function objects with lambda
expressionlambda
allows creating anonymous function (returns function instead of assigning it to a name)lambda arg_1, arg_2,... arg_n: <some_expression>
def add_excl(s): # function definition always binds function object to a variable
return s + '!'
add_excl('Function')
'Function!'
add_excl = lambda s: s + '!' # typically, lambda function wouldn't be assigned to a variable
add_excl('Lambda')
'Lambda!'
def add_five():
return lambda x: x + 5
af = add_five()
af # 'af' is just a function, which is yet to be invoked (called)
<function __main__.add_five.<locals>.<lambda>(x)>
af(10) # Here we call a function and supply 10 as an argument
15
[x ** 2 for x in range(10)] # Could be faster, more 'pythonic'
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
list(map(lambda x: x**2, range(10))) # More functional in style, similar to R
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
def factorial(x):
"""Calculates factorial of x!
Takes one integer as an input
Returns the factorial of that integer
"""
if x == 1:
return x
else:
return x * factorial(x-1)
factorial(5)
120
.py
file with Python defitions and statementsimport
statementimport <module_name>
<module_name>.<object_name>
import <module_name> as <new_name>
<new_name>.<object_name>
from <module_name> import <object_name>
<object_name>
import statistics # Import all objects (functions) from module 'statistics'
from math import sqrt # Import only function 'sqrt' from module 'math'
fib = [0, 1, 1, 2, 3, 5]
statistics.mean(fib) # Mean
2
statistics.median(fib) # Median
1.5
sqrt(25) # Square root
5.0
Module | Description |
---|---|
datetime |
Date and time types |
math |
Mathematical functions |
random |
Random numbers generation |
statistics |
Statistical functions |
os.path |
Pathname manipulations |
re |
Regular expressions |
pdb |
Python Debugger |
timeit |
Measure execution time of small code snippets |
csv |
CSV file reading and writing |
pickle |
Python object serialization (backup) |