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
Q

Copy

A

import copy
new_list = copy.deepcopy(old_list)

26
Q

Step sizes, and reverse order

A

same as primes[0:5:2]

primes = (2, 3, 5, 7, 11)

primes[::2]
(2, 5, 11)

# 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
Q

Unpacking with *

A

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
Q

Tuples preferred way to return multiple values

A

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
Q

Varying number of args

A

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
Q

Iterate over two variables at the same time

A

odd = (1, 3, 5)
even = (2, 4, 6)
for i, j in zip(odd, even):
… print(i + j)

3
7
11

31
Q

Get attributes

A

dir(x), or dir(tuple)

32
Q

Count instances in a tuple

A

nums = (1, 4, 6, 22, 3, 5, 2, 1, 51, 3, 1)
nums.count(3)
2
nums.count(31)
0

33
Q

List assignment not intuitive to me

A

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
Q

remove things from lists

A

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
Q

replace multiple values of a list with one value

A

a = [0,1,2]
a[:2]=[-1]*2
a
[-1, -1, 2]

a[:2]=-1 does not work

36
Q

if else one line

A

isApple = True if fruit == ‘Apple’ else False

37
Q

F strings

A

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
Q

F strings with equals sign

A

variable = “hello”

print(f”{variable = }”)
variable = ‘hello’

Don’t need the spaces, but probably nine to have.

39
Q

** and args

A

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
Q

**and dictionary

A

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
Q

Set

A

duplicates are automatically removed

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}

set([3, 2, 11, 3, 5, 13, 2])
{2, 3, 5, 11, 13}

set(‘initialize’)
{‘a’, ‘n’, ‘t’, ‘l’, ‘e’, ‘i’, ‘z’}

42
Q

Set operations

A

union of two sets: color_1 | color_2

color_1 = {‘teal’, ‘light blue’, ‘green’, ‘yellow’}
color_2 = {‘light blue’, ‘black’, ‘dark green’, ‘yellow’}

color_1.union(color_2)
{‘light blue’, ‘green’, ‘dark green’, ‘black’, ‘teal’, ‘yellow’}

color_1.intersection(color_2)
{‘light blue’, ‘yellow’}

color_1.difference(color_2)
{‘teal’, ‘green’}

color_2.difference(color_1)
{‘dark green’, ‘black’}

# i.e. union of previous two operations: color_1 ^ color_2
color_1.symmetric_difference(color_2)
{‘green’, ‘dark green’, ‘black’, ‘teal’}

43
Q

Change sets in place and add elements

A

union

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’}

color_1.update(color_2)
color_1
{‘light blue’, ‘green’, ‘dark green’, ‘black’, ‘teal’, ‘yellow’}

color_2.add(‘orange’)
color_2
{‘black’, ‘yellow’, ‘dark green’, ‘light blue’, ‘orange’}

44
Q

API endpoints

A

Specific site on an API site, e.g. /routes to get routes for where to go.

45
Q

API request and status code

A

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