Hi, everyone, here's what we did this week:
New Homework - Questions 7 and 9
Question 5 homework solution from last class:
A different type of loop. For loops run on an iterable, and while loops run on a condition. Think of it as a loop with a built-in if statement. Every iteration of the loop, the given condition will be checked to make sure it's still True. If it has become False between the beginning of this loop and the last time it was checked at the beginning of the last loop, then the loop will terminate.
The danger with while loops is that they will run forever. Make sure you are continuously updating the condition so that you don't create an infinite loop.
An infinite loop looks like this:
a = 0 while True:
while a < 10: print("hello")
^There is nothing in the loops' bodies to change the condition. These loops will run forever.
A proper while loop looks like this:
a = 0
while a < 10:
a += 1
the variable a is being incremented each repetition of the loop, so you know eventually it will reach 10, make the condition False, and stop the loop.
Well, this proper while loop kind of looks like something that could be done easier with a for loop. You're right - while loops are usually not used like this, since for loops can iterate a set number of times so much easier. Here is a for loop that does the same as that while loop:
for I in range(10):
^Here we also iterate 10 times but we don't have to manually declare and increment a variable like we needed to for the while loop. While loops are more useful for when you don't know how many times you will need to repeat a section of code. You just know what you need to stop at, so make that your condition.
Thanks, everyone. Reach out if you have questions! -Bonnie