Python While Loop
In Python, the while loop allows you to repeat a block of code as long as a specified condition is true. It’s perfect for situations where you need to perform repetitive tasks or when you don’t know in advance how many times a block of code will need to run.
Here are some common ways to use the while loop:
- Repeating tasks: Automate repetitive actions, like printing messages or performing calculations.
- Handling conditions: Keep running code as long as a certain condition is true, such as checking if a counter is less than a set number.
- Creating infinite loops: A while loop can create infinite loops when the condition never becomes false.
What You'll Learn
In this tutorial, you'll learn the basics of the while loop in Python. We'll cover the structure and syntax of the loop and provide practical examples to help reinforce your understanding.
Understanding the while Loop
The basic syntax for a while loop looks like this:
while condition:
# Code block to execute
# Do something
while condition:
# Code block to execute
# Do something
- condition: This is the expression that is evaluated before each loop iteration. The loop will continue to execute as long as the condition evaluates to True.
- Code block: The code inside the loop that gets executed repeatedly as long as the condition is True.
It’s important to ensure that the condition eventually becomes False, or else the loop will run forever (infinite loop)!
Example 1: Simple While Loop
In this example, we will print the numbers 1 to 5 using a while loop.
i = 1
while i < 5:
print(i)
i += 1
i = 1
while i < 5:
print(i)
i += 1
How It Works:
- i = 1: This initializes the variable i to 1.
- while i <= 5:: This condition keeps the loop running as long as i is less than 5.
- print(i): This prints the current value of i.
- i += 1: This increments i by 1 after each iteration to ensure that the condition eventually becomes False and the loop stops.
- Important: If you forget to increment the variable i, the loop will run indefinitely, resulting in an infinite loop. Always ensure that the loop condition will eventually become False.
Output
1
2
3
4
1
2
3
4

Example 2: Print Even Numbers from 1 to 20
In this example, we’ll use a while loop to print even numbers between 1 and 20.
i = 2
while i <= 20:
print(i)
i += 2
i = 2
while i <= 20:
print(i)
i += 2
How It Works:
- i = 2: We start from 2, the first even number.
- while i <= 20: The loop runs as long as i is less than or equal to 20.
- print(i): Prints the current even number.
- i += 2: Increments i by 2 to move to the next even number.
Output
2
4
6
8
10
12
14
16
18
20
2
4
6
8
10
12
14
16
18
20
Example 3: Sum of Digits of a Number
In this example, we’ll use a while loop to calculate the sum of digits of a given number.
num = 1234
sum = 0
while num > 0:
digit = num % 10
sum += digit
num = num // 10
print("Sum of digits is:", sum)
num = 1234
sum = 0
while num > 0:
digit = num % 10
sum += digit
num = num // 10
print("Sum of digits is:", sum)
How It Works:
- num = 1234: The number whose digits we want to sum.
- digit = num % 10: Extracts the last digit of the number.
- sum += digit: Adds the digit to the running total.
- num = num // 10: Removes the last digit from the number.
- The loop continues until num becomes 0.
Output
Sum of digits is: 10
Sum of digits is: 10
Example 4: Infinite Loop
In this example, we’ll create an infinite loop that continuously prints a message.
while True:
print("This is an infinite loop!")
while True:
print("This is an infinite loop!")
How It Works:
- while True: Since True is always true, the loop will run indefinitely unless manually stopped.
- print("This is an infinite loop!"): This is the code inside the loop that will be executed over and over.
- Important: This loop will continue to run indefinitely, which can freeze your browser or application. To stop it, follow the instructions based on your operating system:
- Windows: Press Ctrl + C in the terminal or command prompt to stop the loop.
- Mac: Press Command + C in the terminal to stop the loop.
- Linux: Press Ctrl + C in the terminal to stop the loop.
Exercises
Try out the following exercises to practice using the while loop.
1. Write a program that prints all numbers from 1 to 10 using a while loop.
# Exercise 1: Print numbers from 1 to 10
i = 1
while i <= 10:
print(i)
i += 1
# Exercise 1: Print numbers from 1 to 10
i = 1
while i <= 10:
print(i)
i += 1
2.Write a program that prints the sum of numbers from 1 to a given number (e.g., 10).
# Exercise 2: Sum numbers up to a given number
num = 10
sum = 0
i = 1
while i <= num:
sum += i
i += 1
print("The sum is:", sum)
# Exercise 2: Sum numbers up to a given number
num = 10
sum = 0
i = 1
while i <= num:
sum += i
i += 1
print("The sum is:", sum)
3. Write a program that prints all even numbers from 1 to 20 using a while loop.
# Exercise 3: Print even numbers from 1 to 20
i = 2 # Start from the first even number
while i <= 20:
print(i)
i += 2 # Increment by 2 to get the next even number
# Exercise 3: Print even numbers from 1 to 20
i = 2 # Start from the first even number
while i <= 20:
print(i)
i += 2 # Increment by 2 to get the next even number
*Tip: After completing an exercise, feel free to experiment with different loop conditions to see how the code behaves!
Frequently Asked Questions
What is a while loop in Python?
What is a while loop in Python?
A while loop in Python allows you to repeatedly execute a block of code as long as a given condition is True.
How does a while loop differ from a for loop?
How does a while loop differ from a for loop?
A while loop continues to run as long as a condition remains true, whereas a for loop runs a set number of times or iterates over a sequence like a list or string.
Can I create an infinite loop with a while loop?
Can I create an infinite loop with a while loop?
Yes! You can create an infinite loop using while True. Be cautious—these can crash your program if not handled properly.
What happens if the while loop condition is never false?
What happens if the while loop condition is never false?
If the condition in a while loop never becomes False, the loop runs forever—this is known as an infinite loop and can cause your program to hang.
How do I break out of a while loop?
How do I break out of a while loop?
Use the break statement inside your while loop to exit it immediately, regardless of the condition.
What's Next?
Next, you'll learn about for loops, which are another way to repeat tasks in Python but with a fixed number of iterations. You'll also explore how to control the flow of loops using the break and continue statements.