Python Many From Learn By Example Github Flashcards

1
Q

_

A

Refers to previous result

3*7
21

_*2
42

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Division without remainder , modulo

A

//

33//10
3

32 % 10
2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Multi line string

A

triple_quotes.py

print(‘'’hi there.
how are you?’’’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

r strings

A

print(r’item\tquantity’)
item\tquantity

r’item\tquantity’
‘item\tquantity’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

f strings

A

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’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Type

A

num = 42
type(num)
<class ‘int’>

type(22 / 7)
<class ‘float’>

type(‘Hi there’)
<class ‘str’>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

And or not

A

Lowercase

4 > 3.14 and 2 <= 3
True

hi’ == ‘Hi’ or 0 != ‘0’
True

not ‘bat’ < ‘at’
True
num = 0
not num
True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Ifelse one line

A

def absolute(num):
return num if num >= 0 else -num

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Continue

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Sampling/ random

A

rand_number.py

import random

gives back an integer between 0 and 10 (inclusive)
rand_int = random.randrange(11)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Variable taking name depending on program calling it

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Try except

A

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”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Try except else, and also finally

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Raise

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Check something true

A

Assert 2<5

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

join paths

A

os.path.join(workdir,”hello.txt”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

enumerate

A

for index, item in enumerate(L):

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

run command after creating it, metaprogramming

A

execstring = ‘assert ‘ + astring + “,’” + astring + “’”
exec(execstring)

setattr might be helpful also

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

create empty list

A

l = [None] * 10
l
[None, None, None, None, None, None, None, None, None, None]

20
Q

any, all

A

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).

21
Q

flatten list

A

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]

22
Q

Tuple declarations

A

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), ())

23
Q

Tuple from iterable

A

chars = tuple(‘hello’)
chars
(‘h’, ‘e’, ‘l’, ‘l’, ‘o’)
tuple(range(3, 10, 3))
(3, 6, 9)

24
Q

Indexing from end

A

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)

25
Copy
import copy new_list = copy.deepcopy(old_list)
26
Step sizes, and reverse order
primes = (2, 3, 5, 7, 11) # same as primes[0:5:2] primes[::2] (2, 5, 11) # retrieve elements in reverse direction # note that the element at index 1 (stop value) isn't part of the output primes[3:1:-1] (7, 5) # reversed sequence # would help you with the palindrome exercise from Control structures chapter primes[::-1] (11, 7, 5, 3, 2)
27
Unpacking with *
values = ('first', 6.2, -3, 500, 'last') x, *y = values x 'first' y [6.2, -3, 500, 'last'] a, *b, c = values a 'first' b [6.2, -3, 500] c 'last'
28
Tuples preferred way to return multiple values
def min_max(iterable): ... return min(iterable), max(iterable) ... min_max('visualization') ('a', 'z') small, big = min_max((10, -42, 53.2, -3)) small -42 big 53.2
29
Varying number of args
def sum_nums(*args): ... total = 0 ... for n in args: ... total += n ... return total ... sum_nums() 0 sum_nums(3, -8) -5 sum_nums(1, 2, 3, 4, 5) 15
30
Iterate over two variables at the same time
odd = (1, 3, 5) even = (2, 4, 6) for i, j in zip(odd, even): ... print(i + j) ... 3 7 11
31
Get attributes
dir(x), or dir(tuple)
32
Count instances in a tuple
nums = (1, 4, 6, 22, 3, 5, 2, 1, 51, 3, 1) nums.count(3) 2 nums.count(31) 0
33
List assignment not intuitive to me
# list will automatically shrink/expand as needed nums[1:4] = [2000] nums [100, 2000, -2, -3] nums[1:2] = [3.14, 4.13, 6.78] nums [100, 3.14, 4.13, 6.78, -2, -3]
34
remove things from lists
mylist = [4, 6, 8] mylist.pop(2) 8 mylist mylist = [4, 6, 8] del mylist[1] mylist [4,8] mylist = [4, 6, 8] del mylist[-1] mylist [4,6] remove uses the value, not the index mylist = [4, 6, 8] mylist.remove(6) mylist [4,8]
35
replace multiple values of a list with one value
a = [0,1,2] a[:2]=[-1]*2 a [-1, -1, 2] a[:2]=-1 does not work
36
if else one line
isApple = True if fruit == 'Apple' else False
37
F strings
balance = 5425.9292 f"Balance: ${balance:.2f}" 'Balance: $5425.93' heading = "Centered string" f"{heading:=^30}" '=======Centered string========' In the second example, you use the :=^30 format specifier. In this case, you’re telling .format() to format the input value using the = symbol as a filler character. The ^ symbol centers the input value by inserting = symbols on both sides to reach thirty characters. Real Python
38
F strings with equals sign
variable = "hello" print(f"{variable = }") variable = 'hello' Don't need the spaces, but probably nine to have.
39
** and args
def many(**kwargs): ... print(f'{kwargs = }') many() kwargs = {} many(num=5) kwargs = {'num': 5} many(car=5, jeep=25) kwargs = {'car': 5, 'jeep': 25}
40
**and dictionary
Can pass arguments with **mydict def greeting(phrase='hello', style='='): ... print(f'{phrase:{style}^{len(phrase)+6}}') ... greeting() ===hello=== mydict = {'style': '-', 'phrase': 'have a nice day'} greeting(**mydict) ---have a nice day---
41
Set
empty_set = set() empty_set set() Declare with braces, items separated by connas nums = {-0.1, 3, 2, -5, 7, 1, 6.3, 5} # note that the order is not the same as declaration nums {-0.1, 1, 2, 3, 5, 6.3, 7, -5} # duplicates are automatically removed set([3, 2, 11, 3, 5, 13, 2]) {2, 3, 5, 11, 13} set('initialize') {'a', 'n', 't', 'l', 'e', 'i', 'z'}
42
Set operations
color_1 = {'teal', 'light blue', 'green', 'yellow'} color_2 = {'light blue', 'black', 'dark green', 'yellow'} # union of two sets: color_1 | color_2 color_1.union(color_2) {'light blue', 'green', 'dark green', 'black', 'teal', 'yellow'} # common items: color_1 & color_2 color_1.intersection(color_2) {'light blue', 'yellow'} # items from color_1 not present in color_2: color_1 - color_2 color_1.difference(color_2) {'teal', 'green'} # items from color_2 not present in color_1: color_2 - color_1 color_2.difference(color_1) {'dark green', 'black'} # items present in one of the sets, but not both # i.e. union of previous two operations: color_1 ^ color_2 color_1.symmetric_difference(color_2) {'green', 'dark green', 'black', 'teal'}
43
Change sets in place and add elements
Methods like add(), update(), symmetric_difference_update(), intersection_update() and difference_update() will do the modifications in-place. color_1 = {'teal', 'light blue', 'green', 'yellow'} color_2 = {'light blue', 'black', 'dark green', 'yellow'} # union color_1.update(color_2) color_1 {'light blue', 'green', 'dark green', 'black', 'teal', 'yellow'} # adding a single value color_2.add('orange') color_2 {'black', 'yellow', 'dark green', 'light blue', 'orange'}
44
API endpoints
Specific site on an API site, e.g. /routes to get routes for where to go.
45
API request and status code
myparams = {"param1": 42, "param2": 51} response = requests.get("http://some.api.com/someinfo.json", params=myparams) status_code = response.status_code print(response.content) json_data = response.json()