Unlike humans who get bored easily, computers are great at repetitive tasks. They do them fast. We have to have an easier way of having a computer do a repetitive task instead of writing the same line of code over and over and over. We use loops to do this.
For loop
The preferred way when working with lists, dictionaries, or tuples. In a for loop the code will execute a certain number of times.
Example of a for loop:
names = [“Sal”, “Mary”, “Charlie”, “Patty”] for name in Names: print(name)
A for statement will have:
- the for keyword
- a variable name
- The in keyword
- The name of the list, dictionary or tuple
- A colon
- Starting on the next line an indented block of code
The code in the loop is ran 4 times, one time for each element in the list.
The for loop is also used with a built in range() function. This function helps us specify the number of times that we want a for loop to run.
Example of for loop with range() function
total = 0 for num in range(101): total += num print(total)
This loop will add all the numbers from 1 to 100 and then when it’s done going through all the numbers it will print the total.
The start, stop and step arguments to range()
We can change the number in our ranges. We can change the number that we start using and the number we end at (but not included).
for i in range(12, 16): print(i) -> 12 -> 13 -> 14 -> 15
If we use the third argument. The first two arguments are the start and stop values and the third will be the step or the amount that the variable is increased by after each loop.
range(start, stop, step)
for i in range(5, 15, 5): print(i) -> 5 -> 10 -> 15
The range() function is flexible and we can have negative numbers if we even wanted to count backwards
for i in range(5, -1, -1): print(i) -> 5 -> 4 -> 3 -> 2 -> 1 -> 0
While Loop
A while loop the code while something is true and stops when it becomes false. This will make it easy print out all the numbers between 1 and 100
number = 1 while number < 101: print(number) number += 1
A while loop will have:
- The while keyword
- a variable name that we created before the loop
- The condition to be met
- A colon
- Starting on the next line an indented block of code
- Somewhere in the code block there should be a change made to the variable
Notice a couple of things. Our loop will run until number is less than 101. We didn’t use 100 because if we did it would only print to 99. The expression would no longer be true when number got to 100 so we used one larger
We could’ve done something like this
While number <= 100 and this would still run at 100 because 100 is less than or equal to 100.
Most of the time errors with loops happen because of logic (human error) as opposed to us syntax (writing something wrong).
The last line in our code increments number by one. If we were not careful and forgot to add this line to our code we would have what is known as an endless loop because 1 is always less than 101 and the loop would run forever until our computer crashed.
Before running loops make sure that the condition will turn false at some point and not crash our computers.
Looping through Dictionaries
We might have the need to loop through a dictionary to get some values or to count items. This can be done in different ways.
Loop through the keys
favorite_books = { "Harry Potter" : "J.K Rowling", "The BFG": "Roald Dahl", "Pet Sematary": "Stephen King" } for book in favorite_books: print(book) -> Harry Potter -> The BFG -> Pet Sematary
Loop through the values
favorite_books = { "Harry Potter" : "J.K Rowling", "The BFG": "Roald Dahl", "Pet Sematary": "Stephen King" } for author in favorite_books.values(): print(author) -> J.K Rowling -> Roald Dahl -> Stephen King
Loop through all keys and values
favorite_books = { "Harry Potter" : "J.K Rowling", "The BFG": "Roald Dahl", "Pet Sematary": "Stephen King" } for book, author in favorite_books.items(): print(book, ":", author) -> Harry Potter : J.K Rowling -> The BFG : Roald Dahl -> Pet Sematary : Stephen King
Using get and loops to count objects in a dictionary
Let’s say we wanted to count how many people there were on one side of our family.
We have two lists of families one on our mom’s side and one on our dad’s side
mom = ["Charlie", "Martha", "Alexandra", "Stephanie"] dad = ["Mary", "Joe", "Wally"]
We have a dictionary of the family sizes
family_sizes = { "Mary": 2, "Charlie": 2, "Joe": 4, "Wally": 1, "Martha": 3, "Alexandra": 1 }
We want to create a new dictionary of only our moms family size.
mom_family_size = {} for family in family_size: mom_family_size[family] = mom_family_size.get(family, 0)