names_list = ['Amanda', 'John', 'Paul', 'Junior', 'Emily']Iteration
Many datatypes allow for iteration. This section will focus on lists, strings, ranges, and dictionaries as examples. Iteration repeatedly executes a block of code.
Lists
for name in names_list:
print(name)Amanda
John
Paul
Junior
Emily
for name in names_list:
print(name + ' is jumping into Python!')Amanda is jumping into Python!
John is jumping into Python!
Paul is jumping into Python!
Junior is jumping into Python!
Emily is jumping into Python!
Strings
python_string = 'Python'for letter in python_string:
print(letter)P
y
t
h
o
n
Nested Loops
for name in names_list:
for letter in name:
print(letter)A
m
a
n
d
a
J
o
h
n
P
a
u
l
J
u
n
i
o
r
E
m
i
l
y
Ranges
Range can be used to execute code a given number of times. Usage is range(start, stop, step), where stop is required and start and step are optional. Stop is exclusive, meaning that number is not part of the sequence. Examples below help illustrate. Note, Python is a 0 based indexing system.
for i in range(5):
print(i)0
1
2
3
4
for i in range(1, 5):
print(i)1
2
3
4
for i in range(1, 10, 3):
print(i)1
4
7
for i in range(1, 10):
if i > 3:
print(i)4
5
6
7
8
9
Enumerate
Enumerate is a built-in function to add a counter to iteratable objects like lists.
for i, name in enumerate(names_list):
print(str(i) + ' - ' + name)0 - Amanda
1 - John
2 - Paul
3 - Junior
4 - Emily
Dictionaries
Dictionaries hold mapped key-value pairs. They are iterable, but must be handled differently than lists. keys will iterate over the keys, while values iterates over the values, and items iterates over both.
my_dict = {'a': 0, 'b': 1, 'c': 2}for k in my_dict.keys():
print(k)a
b
c
for v in my_dict.values():
print(v)0
1
2
# Why does this one not work?
for k, v in my_dict.items():
print(k + ' - ' + v)--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[15], line 3 1 # Why does this one not work? 2 for k, v in my_dict.items(): ----> 3 print(k + ' - ' + v) TypeError: can only concatenate str (not "int") to str
# This one does though!
for k, v in my_dict.items():
print(k + ' - ' + str(v))a - 0
b - 1
c - 2
Dictionary Lookup
Dictionary mapping is usefulf in many contexts. The key of a dictionary can be used to lookup the corresponding value.
Syntax: dict[key].
for k in my_dict.keys():
print(my_dict[k])0
1
2
Flow Control
By default, code is executed from the top to bottom of a script. Flow control is used for more advanced execution that may include repeating blocks, skipping conditions, early exits, and error handling. The ‘if-elif-else’ conditional statement is the most commonly used method of flow control in Python.
When combined with iteration and DRY, very little code can have very impactful results.
If-Elif-Else
The most commonly used flow control in Python. Run the cells below and edit to make x the magic number.
x = 28if x == 23:
print('The magic number!')
elif x > 23:
print('This number is too big...')
else:
print('This number is too small')This number is too big...
Iteration and Flow
for name in names_list:
if 'a' in name:
print(name)Amanda
Paul
for i, name in enumerate(names_list):
if i > 2:
print(name)Junior
Emily
Bring It All Together
Final example uses enumerate with list iteration and multiple if statements. Only one of each if-elif-else will be be executed.
lucky_numbers = [42, 3, 27, 0, -13, 999, 6]for i, x in enumerate(lucky_numbers):
print(f'Index number is {i}.')
print(f'List number is {x}.')
if i == x:
print('Number is lucky! Match Found!')
elif i > x:
print('Not lucky-index value is too high...')
elif i < x:
print('Not lucky-index value is too low...')
else:
print('How did we get here?!')
# Second if statement
if x > 0:
print('Positive vibes!')
elif x < 0:
print('Negative vibes!')
else:
print('No vibes found at all.....')
print('\n') # prints a new-line for spacingIndex number is 0.
List number is 42.
Not lucky-index value is too low...
Positive vibes!
Index number is 1.
List number is 3.
Not lucky-index value is too low...
Positive vibes!
Index number is 2.
List number is 27.
Not lucky-index value is too low...
Positive vibes!
Index number is 3.
List number is 0.
Not lucky-index value is too high...
No vibes found at all.....
Index number is 4.
List number is -13.
Not lucky-index value is too high...
Negative vibes!
Index number is 5.
List number is 999.
Not lucky-index value is too low...
Positive vibes!
Index number is 6.
List number is 6.
Number is lucky! Match Found!
Positive vibes!