5 - Python Statements Flashcards
Here’s the general format for a for loop in Python:
for item in object:
statements to do stuff
The ‘else’ statement looks like:
for num in list1:
if num % 2 == 0:
print(num)
else:
print(‘Odd number’)
Iterating through a sequence that contains tuples, this is ‘tuple unpacking’, and it looks like:
Now with unpacking!
list2 = [(2,4),(6,8),(10,12)]
for tup in list2:
print(tup)
(2, 4)
(6, 8)
(10, 12)
for (t1,t2) in list2:
print(t1)
2
6
10
Iterating through Dictionaries, returning just the keys looks like:
d = {‘k1’:1,’k2’:2,’k3’:3}
k1
k2
k3
Iterating through Dictionaries, returning just the keys and values looks like:
Dictionary unpacking
for k,v in d.items():
print(k)
print(v)
Sorted list of dictionary values:
sorted(d.values())
[1, 2, 3]
A ‘while’ loop with an ‘else’ statement looks like”:
x = 0
while x < 10:
print(‘x is currently: ‘,x)
print(‘ x is still less than 10, adding 1 to x’)
x+=1
else:
print(‘All Done!’)
The ‘break’ keyword does what?
break: Breaks out of the current closest enclosing loop.
The continue keyword does what?
continue: Goes to the top of the closest enclosing loop
What does ‘pass’ do?
pass: Does nothing at all.
What function allows you to generate integers?
Notice how 11 is not included, up to but not including 11, just like slice notation!
range()
list(range(0,11))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
How do you save a Range() to a list?
Notice how 11 is not included, up to but not including 11, just like slice notation!
list(range(0,11))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
What does ‘enumerate’ do:
Notice the tuple unpacking!
Keeping track of how many loops you’ve gone through is so common, that enumerate was created so you don’t need to worry about creating and updating this index_count or loop_count variable.
for i,letter in enumerate(‘abcde’):
print(“At index {} the letter is {}”.format(i,letter))
At index 0 the letter is a
At index 1 the letter is b
At index 2 the letter is c
At index 3 the letter is d
At index 4 the letter is e
also
for i in enumerate(‘abcde’):
print(i)
(0, ‘a’)
(1, ‘b’)
(2, ‘c’)
(3, ‘d’)
(4, ‘e’)
What does zip() do?
You can use the zip() function to quickly create a list of tuples by “zipping” up together two lists.
A zip() function looks like:
mylist1 = [1,2,3,4,5]
mylist2 = [‘a’,’b’,’c’,’d’,’e’]
zip(mylist1,mylist2)
list(zip(mylist1,mylist2))
[(1, ‘a’), (2, ‘b’), (3, ‘c’), (4, ‘d’), (5, ‘e’)]