leafleafleafDocy banner shape 01Docy banner shape 02Man illustrationFlower illustration

Python while loop Conditional Statement

Estimated reading: 4 minutes 21 views

We have previously learned about conditional statements, which allow the following block of code to be executed once if a condition is true. Loops, on the other hand, allow the same piece of code to be executed multiple times if a condition remains true. For example, as long as school is not over, we have to go on and on class after class; in a marathon, as long as the final sprint is not reached, the athlete will continue to run.

A loop is actually the execution of a piece of code repeatedly based on a condition. Sometimes it repeats a certain number of times; sometimes it repeats until a condition is True; sometimes it repeats until the user stops it. In this tutorial, we will learn about while loops.

while loop

A while loop is the simplest type of loop that repeats code while a condition is true. That is, the while loop repeatedly executes its body until a certain condition is no longer True. Writing a while loop is like saying, “While this condition is true, keep doing this; when the condition becomes false, stop doing this.”

In Python, a while statement consists of the following parts:

  • while keyword;
  • condition;
  • colon;
  • An indented block of code starting on the next line.

Just like the if statement, if the condition is True, the code block of the while loop is executed. But unlike the if statement, the while loop will check the condition again after executing the code block, and if the condition is still true, it will run the code block again. The loop repeats until the condition is False.

while loop example

Let’s look at an example. Suppose you have trouble falling asleep at night and want to count sheep. However, if you are a programmer, you can write a piece of code to count sheep for you, and when the count reaches 30, you can go to sleep. code show as below.

sheepCounted=0
while sheepCounted<30:
    print("I have counted "+str(sheepCounted)+ " sheep.")
    sheepCounted=sheepCounted+1
print("I fall asleep.")

We first create a variable called sheepCounted and set its value to 0. When starting the while loop, check to see if sheepCounted is less than 30. Because the value of sheepCounted is now 0, which is less than 30, the statement in the code block (the body of the loop) is executed.

  • First, the statement “I have counted “+str(sheepCounted)+ ” sheep.” will display “I have counted 0 sheep.” on the screen;
  • Next, the statement sheepCounted=sheepCounted+1 will add 1 to the value of sheepCounted;
  • Now, the value of sheepCounted is 1. Then go back to the beginning of the loop and judge again whether the sheepCounted is less than 30.

This is repeated over and over again until sheepCounted becomes 30, at which time the condition becomes false (30 is not less than 30), and the program jumps out of the loop. At this time, “I fall asleep.” will be printed, as shown in Figure 1.

python endless loop example

Figure 1
The while loop is also very useful when the user is asked to enter the correct input. We can continue to judge until the user input is correct. Suppose we want the user to enter Johnson, as long as the user does not enter the correct content (or the format of the input content does not meet the requirements), we can always let the user re-enter, the code is as follows.

name=input("Please input my son's name: ")
while name!="Johnson":
    print("I'm sorry, but the name is not valid.")
    name=input("Please input my son's name: ")
print("Yes. "+name+" is my son.")

In the above example, the block of code below the while loop will continue to run until the statement name!=”Johnson” is False. That is, this loop will continue to run until the user input is Johnson, that is, the result of name!=”Johnson” is False. Figure 2 is an example of the program’s output.

python while loop exampl - robort
python while loop example

While loop output example
Figure 2

endless while loop

When using loops, remember: if the condition we set will never be False, the loop will go into an infinite loop (unless you close or exit Python).

For example, in the sample program for counting sheep, if you remove the sentence sheepCounted=sheepCounted+1, then sheepCounted will always remain 0, and the program will not end. The results obtained are shown in Figure 3.

python endless loop example
Python endless loop example


Image 3
 Let’s look at another example from earlier, where the loop is only exited when the user enters Johnson. Code show as below.

name=""
while name!="Johnson":
    name=input("Please input a name: ")

But if the user can never enter Johnson correctly, the program “asks” forever, as shown in Figure 4.

python looping

Leave a Comment

CONTENTS