concept while loop in category raspberry pi

appears as: while loop, The while loop
Hello Raspberry Pi!: Python programming for kids and other beginners

This is an excerpt from Manning's book Hello Raspberry Pi!: Python programming for kids and other beginners.

In the case of your guessing game, you’re giving the game player five tries to guess the parrot’s age. Python has several types of loops: you’ll use the while loop. A while loop repeats over and over until a certain condition or circumstance is no longer true. What it repeats is for you to decide. Each time through the loop, before the program repeats the instructions you gave it, it checks that condition.

Let’s look at how you can use a while loop with your if statement to give the user only five guesses. To help, you’ll create a variable named number_of_guesses to keep track of the guesses.

Listing 4.8. Using a while loop to repeat instructions

Notice how you have to rearrange the code in the program a bit. First you start the while loop, and then you ask the user to input their guess. Also notice that the code to repeat in the while loop is indented (shifted over four spaces). Let’s take a closer look at the key elements of the while loop (see figure 4.13).

Figure 4.13. Think of the logic you’re trying to create, and then translate it into your code. When you need to repeat something, you can use a while loop. When you need to check whether something is True or False, you can use an if statement.

There is a special thing about a while loop: you must indent all the code that you want the loop to repeat (like you did for if statements). Each line should be indented four spaces from the left (you measure this from where you type the w in while). Similarly, you stop indenting code when you want the while loop to end. Code that isn’t indented is outside the while loop and is only run after the while loop finishes.