2. Loop and Flow Control Flashcards
Control flow
if:
elif:
else:
syntax of a for loop
my_interable = [1,2,3]
for xxx in my_iterable:
print( xxx)
tuple unpacking
Duplicate the structure in the iterables
For (a,b) in my_tuples:
print(b)
Also mean breaking up a tuple into variable
name, hours = tuple(‘Mary’,100)
tuple unpacking in dictionary
by default dictionary loop through the key only
For key,value in d.items():
print(value)
while loop
while boolean_condition:
#do something
else:
#do something diff
control flow in loop (3 methods)
break: stop the loop
continue: stop and go back to first line
pass: do nothing
enumerate function
Zip a count with the iterable object and return a tuple
word = ‘abcde’
for item in enumerate(word):
print(item)
combine two list together
for item in zip(mylist1, mylist2):
print(item)
return tuples
list comprehension
quick way to replace for loop along with .append()
mylist = [x for x in 'word'] mylist = [x**2 for x in range(1,11) ] mylist = [x for x in range(1,11) if x % 2 == 0
looping through a string (or list)
for i in range(len(text))
for/while:
else:
else will be run at the end when the loop is done or while condition is no longer true; break will break the whole loop and break the else as well
1) if x:
2) if not x
3) if x is not None
1) if x, means if it is something (i.e. not none or not empty), do something
2) if not x, means do something if none/empty
3) similar to 1 but empty != None anymore
see if x is really not None