Course Content
Introduction to Python
Introduction to Python
Explore the while Loop in Python
In programming, you often need your code to run repeatedly while a certain condition remains true.
Think of it like riding the subway you stay on the train until you reach your stop. If your destination is Station C, you might pass Station A and Station B before arriving at Station C.
You can achieve this behavior using a while
loop, which follows this structure:
You can use this loop to print all numbers up to 10
.
# Assign starting number (counter) i = 1 # While loop will print all the numbers to 10 while i < 10: # Condition print(i, end = ' ') # Action i = i + 1 # Increasing variable
Note
By default, the
print()
function outputs each result on a new line. However, using theend=' '
argument, we can separate multipleprint()
outputs with a space instead.
The loop's logic is shown above. Notice that the statement i = i + 1
is included inside the loop. Without this line, the loop would run indefinitely because the condition 1 < 10
would always remain True
. To prevent infinite loops, it's essential to ensure the loop's condition eventually becomes False
.
Thanks for your feedback!