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

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

  1. create a variable game and assign it True (when it turns to False game stops)
  2. create a while loop to check game variable
  3. input name and color to two variables
  4. create a variable cont to ask user if he want to continue
  5. with a while loop ask user if he wants to continue 

You can view a sample solution here.