πWeek 7 - Lab Intro#
In this lab introduction we will briefly discuss the topic of looping.
Looping#
for
loops#
for
loops let you run the same block of code for a predetermined number of iterations.
syntax: for [variable name] in [iterable]
for i in range(10):
print(i)
0
1
2
3
4
5
6
7
8
9
the range
function#
The range()
function creates an iterable over integers. It can have up to three arguments (start, stop, step).
# loop from 2 up to (not including) 20, stepping by 3
for i in range(2,20,3):
print(i)
2
5
8
11
14
17
with 2 arguments: (start, stop, 1)
# loop from 6 up to (not including) 10
for i in range(6,10):
print(i)
6
7
8
9
As before, with 1 argument: (0, stop, 1)
# loop from 0 up to (not including) 5
for i in range(5):
print(i)
0
1
2
3
4
looping over a list#
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
for d in days:
print(d)
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
looping over a string#
message = "Hello World!"
for letter in message:
print(letter)
H
e
l
l
o
W
o
r
l
d
!
looping over a dictionary#
A for
loop over a dictionary iterates over the keys.
fruit_inventory = {"apple" : 6,
"banana" : 2,
"orange" : 4}
for f in fruit_inventory:
print(f)
apple
banana
orange
If we want the values as well, we can use [dict_name].items()
.
fruit_inventory = {"apple" : 6,
"banana" : 2,
"orange" : 4}
for f in fruit_inventory.items():
print(f)
('apple', 6)
('banana', 2)
('orange', 4)
To separate each (key, value) tuple, we can provide to variables to the for loop.
fruit_inventory = {"apple" : 6,
"banana" : 2,
"orange" : 4}
for fruit_name, quantity in fruit_inventory.items():
print(f"There are {quantity} {fruit_name}s in stock.")
the enumerate
function#
We can use the enumerate function to loop over an iterable with (index, object) pairs.
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
for d in enumerate(days):
print(d)
We can use two variables to βunpackβ the tuple.
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
for i, d in enumerate(days):
print(f"{d} is day #{i+1}.")
while
loops#
while
loops keep iterating while some condition is True
.
syntax: while [condition]
i = 0
while i < 10:
print(i)
i += 1
0
1
2
3
4
5
6
7
8
9
Notice that this is the same as the for
loop we saw previously:
for i in range(10):
print(i)
0
1
2
3
4
5
6
7
8
9
Make sure the while
loop condition will eventually become False
. You donβt want to loop forever!
Run this at your peril:
# loops forever
i = 0
while i < 10:
print(i)
If you already know how many times the loop needs to run, it is easier/cleaner to use a for
loop.
Hereβs an example where while
is required.
input_string = input("Please enter your favorite number:")
while not input_string.isnumeric():
input_string = input("Not a number. Try again:")
print(f"{input_string} is your favorite number.")
Please enter your favorite number: five
Not a number. Try again: six
Not a number. Try again: 6
6 is your favorite number.
We need a while
loop (rather than a for
loop) because we donβt know how many times the user will mess up and enter a non-number.
break
and continue
#
break
statements#
The keyword break
causes a loop to immediately terminate.
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
for d in days:
if len(d) > 6:
break
print(d)
Sunday
Monday
continue
statements#
The keyword continue
causes a loop to immediately terminate the current iteration, and move to the next one.
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
for d in days:
if len(d) > 6:
continue
print(d)
Sunday
Monday
Friday
Nested loops#
Loops can be nested. The following example uses nested for
loops to count in binary from 0 to 7.
for i in range(2):
for j in range(2):
for k in range(2):
print(f"{i}{j}{k}")
000
001
010
011
100
101
110
111
Counting with dictionaries#
Dictionaries are a natural choice of data structure when you want to count different things.
Consider the following example with counting suits in a hand of playing cards.
# cards are represented by a tuple: `(value, suit)`
hand_of_cards = [("ace", "spades"),("jack", "diamonds"),("queen", "spades"),("four", "spades"), ("jack", "hearts")]
# initialize a dictionary for counting the suits, all starting at 0
suit_counts = {"clubs" : 0,
"diamonds" : 0,
"hearts" : 0,
"spades" : 0}
# loop through the hand of cards, unpacking the tuple into value and suit variables
for value, suit in hand_of_cards:
# increment the value located at key=suit
suit_counts[suit] += 1
# print the final dictionary of counts
print(suit_counts)
{'clubs': 0, 'diamonds': 1, 'hearts': 1, 'spades': 3}