Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Explore the while Loop in Python | Loops in Python
Introduction to Python
course content

Course Content

Introduction to Python

Introduction to Python

1. First Acquaintance with Python
2. Variables and Types in Python
3. Conditional Statements in Python
4. Other Data Types in Python
5. Loops in Python
6. Functions in Python

book
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.

1234567
# 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
copy

Note

By default, the print() function outputs each result on a new line. However, using the end=' ' argument, we can separate multiple print() 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.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 1
We're sorry to hear that something went wrong. What happened?
some-alt