Python

While loop

Unsure how many times to repeat code?

Python has the while keyword. Unlike the for loop which tests the condition first, the while loop execute the code first. Sometimes we don’t know how long sometimes will take.

A theoretical program could be (pseudocode):

while sun_not_shining:
use jacket
use gloves

which keeps executing the code block until the condition is true.

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

while loop example

Lets build an extended ‘guess the number game’:

 x = 0
while x != 5:
x = int(input("Guess a number:"))

if x != 5:
print("Incorrect choice")

print("Correct")

This will keep asking a number until the number is guessed. This is defined in the line: while x != 5, or in English, “while x is not equal to five, execute”.

Illustrated:
while loop

The program keeps repeating the code block while the condition (x!=5) is True. Once x equals 5, the program continues.

Infinite loops

If a condition in a while loop is never met, it could cause the program to run forever or to freeze/crash.
 

Previous Post Next Post

Cookie policy | Privacy policy | ©