Module 4 - Section 1 - While and Functions
4.1.1 - While loop
Oddly enough, a while loop can be used anywhere that a for loop is used. It can be used to loop until an increment variable reaches a certain value. So why we have a for loop if a while loop can do everything? The for loop is simpler to use and code. A for loop that looks like this:
for i in range(10):
...can be done with a while loop that looks like this:
i = 0
while i < 10:
i = i + 1
To achieve the same using a while loop we have to:
- Create a "sentinel" variable to count the number of times the loop has been executed
- Assign a starting value of zero to the above variable
- Create a condition and use it to get out of the loop when it becomes False
- Increase the "sentinel" variable
So a better use of the while loop is to ask for a reply from the user.
Copy the code to Thonny and save it as test_while (or whatever name you like) :
quit = "n"
while quit == "n":
quit = input("Do you want to quit? ")
What is the result of this code? If you reply n then the code stays in the loop and keeps asking. But if you reply anything else then the code gets out of the loop. It is not perfect but it is a start and you can try to make it better.