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