Python Many From Learn By Example Github Flashcards
_
Refers to previous result
3*7
21
_*2
42
Division without remainder , modulo
//
33//10
3
32 % 10
2
Multi line string
triple_quotes.py
print(‘'’hi there.
how are you?’’’)
r strings
print(r’item\tquantity’)
item\tquantity
r’item\tquantity’
‘item\tquantity’
f strings
restricting number of digits after the decimal point
str1 = ‘hello’
str2 = ‘ world’
f’{str1}{str2}’
‘hello world’
f’{str1}({str2 * 3})’
‘hello( world world world)’
appx_pi = 22 / 7
f’Approx pi: {appx_pi:.5f}’
‘Approx pi: 3.14286’
f’{appx_pi:.3f}’
‘3.143’
f’{32 ** appx_pi:.2e}’
‘5.38e+04’
Type
num = 42
type(num)
<class ‘int’>
type(22 / 7)
<class ‘float’>
type(‘Hi there’)
<class ‘str’>
And or not
Lowercase
4 > 3.14 and 2 <= 3
True
hi’ == ‘Hi’ or 0 != ‘0’
True
not ‘bat’ < ‘at’
True
num = 0
not num
True
Ifelse one line
def absolute(num):
return num if num >= 0 else -num
Continue
for num in range(10):
… if num % 3:
… continue
… print(f’{num} * 2 = {num * 2}’)
…
0 * 2 = 0
3 * 2 = 6
6 * 2 = 12
9 * 2 = 18
Sampling/ random
rand_number.py
import random
gives back an integer between 0 and 10 (inclusive)
rand_int = random.randrange(11)
Variable taking name depending on program calling it
The special variable __name__ will be assigned the string value ‘__main__’ only for the program file that is executed. The files that are imported inside another program will see their own filename (without the extension) as the value for the __name__ variable.
An example of a dunder variable
Try except
try_except.py
from math import factorial
while True:
try:
num = int(input(‘Enter a positive integer: ‘))
print(f’{num}! = {factorial(num)}’)
break
except ValueError:
print(‘Not a positive integer, try again’)
Using as:
try:
num = 5 / 0
except ZeroDivisionError as e:
print(f’oops something went wrong! the error msg is:\n”{e}”’)
oops something went wrong! the error msg is:
“division by zero”
Try except else, and also finally
try_except_else.py
while True:
try:
num = int(input(‘Enter an integer number: ‘))
except ValueError:
Finally happens no matter what
try:
num = int(input(‘Enter a positive integer: ‘))
if num < 0:
raise ValueError
except ValueError:
print(‘Not a positive integer, run the program again’)
else:
print(f’Square root of {num} is {num ** 0.5:.3f}’)
finally:
print(‘\nThanks for using the program, have a nice day’)
print('Not an integer, try again') else: print(f'Square of {num} is {num ** 2}') break
Raise
def sum2nums(n1, n2):
… types_allowed = (int, float)
… if type(n1) not in types_allowed or type(n2) not in types_allowed:
… raise TypeError(‘Argument should be an integer or a float value’)
… return n1 + n2
…
sum2nums(3.14, -2)
1.1400000000000001
sum2nums(3.14, ‘a’)
Traceback
Check something true
Assert 2<5
join paths
os.path.join(workdir,”hello.txt”)
enumerate
for index, item in enumerate(L):
run command after creating it, metaprogramming
execstring = ‘assert ‘ + astring + “,’” + astring + “’”
exec(execstring)
setattr might be helpful also
create empty list
l = [None] * 10
l
[None, None, None, None, None, None, None, None, None, None]
any, all
any(iterable)
Return True if any element of the iterable is true. If the iterable is
empty, return False. Equivalent to
all all
all(iterable)
Return True if all elements of the iterable are true (or if the iterable
is empty).
flatten list
using a listcomp with two ‘for’
vec = [[1,2,3], [4,5,6], [7,8,9]]
[num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Tuple declarations
can also use: empty_tuple = tuple()
empty_tuple = ()
note the trailing comma, otherwise it will result in a ‘str’ data type
# same as ‘apple’, since parentheses are optional here
one_element = (‘apple’,)
multiple elements example
dishes = (‘Aloo tikki’, ‘Baati’, ‘Khichdi’, ‘Makki roti’, ‘Poha’)
mixed data type example, uses expressions as well
mixed = (1+2, ‘two’, (-3, -4), empty_tuple)
mixed
(3, ‘two’, (-3, -4), ())
Tuple from iterable
chars = tuple(‘hello’)
chars
(‘h’, ‘e’, ‘l’, ‘l’, ‘o’)
tuple(range(3, 10, 3))
(3, 6, 9)
Indexing from end
len(primes) - 1 = 4, so this is same as primes[4]
primes = (2, 3, 5, 7, 11)
primes[-1]
11
primes[-1:]
(11,)
primes[-2:]
(7, 11)