Python Flashcards
(25 cards)
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’)
Sort lists
list.sort()
new_list = list.sorted()
defaults to alpha, you can specify sort(key=my_sort_function) to determine what sorts.
Sets
Set items are unordered, unchangeable, and do not allow duplicate values.
set1 = {‘Python’, ‘R’, ‘SQL’}
set2 = set()
set2.add(‘Python’)
Polymorphism
Overwriting parent attribute or function
class Animal:
def age(self):
self.age = 5
class Rabbit(Animal):
def age(self):
self.age = 5
Super
class Emp(): def \_\_init\_\_(self, id, name, Add): self.id = id self.name = name self.Add = Add # Class freelancer inherits EMP class Freelance(Emp): def \_\_init\_\_(self, id, name, Add, Emails): super().\_\_init\_\_(id, name, Add) self.Emails = Emails Emp_1 = Freelance(103, "Suraj kr gupta", "Noida" , "KKK@gmails")
Python
Subprocess Popen
import subprocess Create a subprocess object p = subprocess.Popen(["ls", "-l"]) Get the output of the subprocess output = p.communicate()[0] Print the output print(output)
Subprocess Run
import subprocess subprocess.run(["command", "arg1", "arg2"])
Python - What does the single underline in front of a variable.
_my_variable = 10
this makes a variable private to the flass or function it’s in.
What does the underscore her do
label, has_label, _ = text.partition(‘:’)
The underline is for a returned value you want to throwaway
Python
How do you add or combine lists
list1 = [1, 2] list1.append(3) list1.extend([5, 6]) list2 = [7,8] list2 = list2 + [9,10] list1 += list2 print(list2)