Week 3 - Section 1 - Data types and a bit of gaming
Chapter 4.6 - While
4.6 - While
A while loop is used when a program needs to loop until a particular condition occurs.
Oddly enough, a while loop can be used anywhere a for loop is used. It can be used to loop until an increment variable reaches a certain value. Why 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):
print(i)
...can be done with a while loop that looks like this:
i = 0
while i < 10:
print(i)
i = i + 1
In 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 statement and check when this statement is 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. It is not perfect but it helps and if you can make it better it works better.
As an exercise create a code that asks the user to input his name and then his favorite color and then display a message "Hi name! Your favorite color is color! After that ask the player if he wants to play again and if he replies yes then ask again name and color if replies no exit and in any other case ask again.
Steps
- create a variable game and assign it True (when it turns to False game stops)
- create a while loop to check game variable
- input name and color to two variables
- create a variable cont to ask user if he want to continue
- with a while loop ask user if he wants to continue
You can view a sample solution here.