Python Flashcards
Loop through a dict
for key, value in original_dict.items():
reversed_dict[value] = key
Filter
adults = filter(myFunc, ages)
map
map(function, iterable)
org_list = [1, 2, 3, 4, 5]
# define a function that returns the cube of num
def cube(num):
return num**3
new_list = list(map(cube, org_list))
Generators
to print all
def gen_numbers():
for i in range(1, 11):
yield i
for i in gen_numbers():
Print i
to go through them 1 by 1:
numb = gen_numbers()
print(next(numb))
While Loop
while i <= n:
print(i)
i = i +
for loop
for x in range(0, 3):
print(“We’re on time %d” % (x))
Range
range(min, max_not_included, step)
range(6) will produce 0-5
range(1,11) will produce 1-10
range(1,6,2) will produce 1,3
range(10, 0, -1) will produce a countdown
Exponent
x**3 (cubed)
x**10
Define string that prints when you look at a class
class Elevator:
def __str__(self):
return “Current floor: “ + str(self.current) + “. returned when you call print(elevator) on an instance”
Recursion Example
def sum_positive_numbers(n):
# The base case is n being smaller than 1
if n < 1:
return 0
# Recursion Case
return n + sum_positive_numbers(n - 1)
Help
help(function_or_class)
Returns doc string
Get Values only from a dict
for package in self.packages.values()
Random number
import random
random.randint(1,10)
Get date
import datetime
bd = datetime.date(20223, 5, 30)
hbd = bd + datetime.timedelta(days=162.5)
hbd.strftime(‘%Y-%m-%d’)
now = datetime.datetime.now()
now.year()
Remove an item from a dict
dict.pop(‘key’)