Consider the following code...
print(9 * 1)
print(9 * 2)
print(9 * 3)
print(9 * 4)
print(9 * 5)
This code is repetitive and variable, but the variability is sequential - it just adds one to the right-hand side number each time. In English, we could describe this as "print out the first 5 multiples of 9".
We can simplify this code with a loop!
The while loop syntax:
while <condition>:
<statement>
<statement>
As long as the condition is true, the statements below it are executed.
multiplier = 1
while multiplier <= 5:
print(9 * multiplier)
multiplier += 1
The code is significantly shorter, and it can easily be extended to loop for more or less iterations.
You can change the initial values of the variables used in the condition:
multiplier = 3
while multiplier <= 5:
print(9 * multiplier)
multiplier += 1
You can change the condition:
multiplier = 3
while multiplier <= 10:
print(9 * multiplier)
multiplier += 1
You can change how much the values change between iterations:
multiplier = 3
while multiplier <= 10:
print(9 * multiplier)
multiplier += 2
You can change the computation inside the while loop:
multiplier = 3
while multiplier <= 10:
print(10 * multiplier)
multiplier += 2
Uh oh..
counter = 1
while counter < 5:
total += pow(2, counter)
What one line of code would fix this?
counter += 1
A list is a container that holds a sequence of related pieces of information.
The shortest list is an empty list, just 2 square brackets:
members = []
Lists can hold any Python values, separated by commas:
members = ["Pamela", "Tommy", "Amber"]
ages_of_kids = [0, 2, 8]
prices = [79.99, 49.99, 89.99]
remixed = ["Pamela", 7, 79.99]
Each list item has an index, starting from 0.
temps = [48.0, 30.5, 20.2, 99.0, 52.0]
# Index: 0 1 2 3 4
Access each item by putting the index in brackets:
temps[0] # 48.0
temps[1] # 30.5
temps[2] # 20.2
temps[3] # 99.0
temps[4] # 52.0
temps[5] # 🚫 Error!
Negative indices are also possible:
temps[-1] # 52.0
temps[-2] # 99.0
temps[-6] # 🚫 Error!
Use the global len()
function
to find the length of a list.
attendees = ["Tammy", "Shonda", "Tina"]
print(len(attendees)) # 3
num_of_attendees = len(attendees)
print(num_of_attendees)
🤔 What could go wrong with storing the length?
Python lists are mutable, which means you can change the values stored in them.
Use bracket notation to modify single items in the list:
temps = [48.0, 30.5, 20.2, 99.0, 52.0]
temps[2] = 22.22
temps[-1] = 55.55
What if we change the value of an item beyond the list length?
temps[5] = 111.11 # 🚫 Error!
You can use a standard while
loop:
scores = [80, 95, 78, 92]
total = 0
i = 0
while i < len(scores):
score = scores[i]
total += score
i += 1
😍 Python allows provides a for-in
loop for lists:
for score in scores:
total += score