Skip to main content
Practice

Controlling Loops with the while Statement

The while statement is a construct that repeats a block of code as long as a given condition is True.

The loop terminates when the condition becomes False.

This makes the while loop useful for tasks that need to repeat until a specific condition is met, such as receiving user input.


Basic Structure of the while Loop

A while loop executes the block of code following the colon (:) repeatedly as long as the condition remains true.

Basic Structure of the while Loop
while condition:
code_to_execute

Since the code will repeat infinitely while the condition is true, you must include code that makes the condition false at some point.


Example: Printing Numbers from 1 to 5

Printing numbers from 1 to 5
i = 1

# Repeat as long as i is less than or equal to 5
while i <= 5:
print(i)
# Increment i by 1
i += 1

This code runs print(i) as long as i is less than or equal to 5, then increments i by 1.

The loop will terminate when i is no longer less than or equal to 5 (i.e., when i becomes 6).


What is an Infinite Loop?

An infinite loop is a loop that never ends because the condition always remains true.

Infinite loops can halt a program or consume excessive resources, causing bugs.

It's crucial to define the condition clearly to avoid infinite loops.


Example of an Infinite Loop

Example of an Infinite Loop
i = 1

while i <= 5:
print(i)
# The value of i never changes, so the condition is always true, causing an infinite loop

In the code above, i never increments, so the condition i <= 5 is always true, resulting in an infinite loop.


Preventing Infinite Loops

To prevent infinite loops, ensure that the loop includes code that changes the condition from true to false.

For example, you can increment i or adjust the logic so that the condition eventually becomes false.

Example to Prevent Infinite Loop
i = 1

# Loop terminates when i is greater than or equal to 20
while i < 20:
print(i)
# Increment i by 1
i += 1

When Do We Use the while Loop?

The while loop is useful for performing repetitive tasks until a certain condition is met.


Use Case Example: Repeating Until a Desired Input is Received

You can use a while loop to continuously receive input from a user until they decide to quit.

Repeat until the user inputs 'q'
user_input = ""

# Repeat until the user inputs 'q'
while user_input != "q":
user_input = input("Enter 'q' to quit: ")

This code will keep taking input from the user until they enter 'q'.

Once user_input is 'q', the loop terminates, stopping the input process.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.