While giving a weekend session for a Python user group in New York, I covered a topic on the Python while loop with examples. You should know about the while loop if you want to learn Python. In this tutorial, let me explain Python while looping with examples.
What is a While Loop in Python?
In Python, a while loop is used to repeatedly execute a block of code as long as a given condition is true. This type of loop is particularly useful when you don’t know beforehand how many times you’ll need to execute the loop. The basic syntax of a while loop in Python looks like this:
while condition:
# code block
Here’s a step-by-step breakdown of how it works:
- Condition: The loop starts by checking the condition. If the condition is evaluated as true, the code block inside the loop will execute.
- Code Block: The code inside the loop runs.
- Re-evaluation: After the code block executes, the condition is re-evaluated. If it’s still true, the loop runs again. This process repeats until the condition becomes false.
- Exit: Once the condition is false, the loop exits, and the program continues with the next line of code after the loop.
Check out Do While Loop in Python
Basic Example of While Loop in Python
Let’s start with a simple example of how a while loop works in Python. We’ll write a program that prints the numbers from 1 to 5.
count = 1
while count <= 5:
print(count)
count += 1
In this example:
- We initialize a variable
countwith the value 1. - The while loop checks if
countis less than or equal to 5. - If the condition is true, it prints the value of
countand then incrementscountby 1. - This process repeats until
countbecomes 6, at which point the condition is false, and the loop exits.
When you run this code, the output will be:
1
2
3
4
5
You can see the output in the screenshot below:

Check out Python While Loop Break and Continue
Python While Loop for User Input
A common use case for a while loop is to repeatedly ask for user input until a valid response is received. Let’s create a program that asks the user to enter a positive number.
number = -1
while number <= 0:
number = int(input("Please enter a positive number: "))
if number <= 0:
print("That's not a positive number. Try again.")
print(f"Thank you! You entered: {number}")
In this example:
- We initialize
numberwith a value of -1. - The while loop checks if
numberis less than or equal to 0. - If the condition is true, it prompts the user to enter a positive number.
- If the user enters a non-positive number, it prints an error message and asks again.
- The loop continues until the user enters a positive number.
When you run this code, it will keep asking for a positive number until the user provides one.
Infinite Loops and Breaking Out in Python While Loop
A while loop in Python can potentially become an infinite loop if the condition never becomes false. This can be useful in certain scenarios, but it’s important to use it carefully. You can also use the break statement to exit the loop prematurely.
Here’s an example of an infinite loop that asks the user to guess a secret number:
secret_number = 7
while True:
guess = int(input("Guess the secret number (between 1 and 10): "))
if guess == secret_number:
print("Congratulations! You guessed it right.")
break
else:
print("Wrong guess. Try again.")
In this example:
- The while loop runs indefinitely because the condition is always
True. - Inside the loop, the user is prompted to guess the secret number.
- If the guess is correct, it prints a congratulatory message and uses
breakto exit the loop. - If the guess is incorrect, it prints an error message, and the loop continues.
You can see the output in the screenshot below:

Check out How to Stop a While Loop in Python
Python Program Examples Using While Loop
Now, to understand how Python while looping works more, let me show you three real-time examples.
1. Reading User Input Until a Condition is Met
One common use case for a while loop is to repeatedly prompt the user for input until they provide a valid response. For instance, let’s create a program that asks the user to enter a positive integer. If the user enters a negative number or zero, the program will continue to prompt them until a valid input is received.
Here is the complete Python code.
# Example 1: Reading user input until a positive integer is entered
user_input = int(input("Enter a positive integer: "))
while user_input <= 0:
print("That's not a positive integer!")
user_input = int(input("Please enter a positive integer: "))
print(f"Thank you! You entered {user_input}.")
In this example, the while loop ensures that the user is repeatedly asked for input until a positive integer is provided. The condition user_input <= 0 keeps the loop running as long as the input is not a positive integer.
Here is the output in the screenshot below; check out the exact output:

2. Calculating the Sum of Digits of a Number
Another practical example is calculating the sum of the digits of a given number in Python. This can be efficiently done using a while loop that processes each digit of the number individually.
Here is an example.
# Example 2: Calculating the sum of digits of a number
number = int(input("Enter a number: "))
sum_of_digits = 0
while number > 0:
digit = number % 10
sum_of_digits += digit
number = number // 10
print(f"The sum of the digits is {sum_of_digits}.")
Here, the while loop continues to run as long as number is greater than zero. In each iteration, it extracts the last digit of the number using the modulus operator %, adds it to sum_of_digits, and then removes the last digit by performing integer division by 10.
You can see the output in the screenshot below:

3. Implementing a Simple Password Check
A while loop can also be used to implement a simple password check mechanism, where the user is prompted to enter a password until they get it right. This can be useful in scenarios where you need to ensure secure access.
Here is the complete example and the code.
# Example 3: Simple password check
correct_password = "python123"
user_password = input("Enter the password: ")
while user_password != correct_password:
print("Incorrect password. Try again.")
user_password = input("Enter the password: ")
print("Access granted.")
In this example, the while loop keeps prompting the user to enter the password until the correct password is provided. The condition user_password != correct_password ensures that the loop continues to run until the user enters the correct password.
You can see the output in the screenshot below:

Conclusion
The while loop is very useful in Python that allows you to execute a block of code repeatedly based on a condition. In this tutorial, I have explained how to use while loop in Python with examples.
You may also like the following tutorial:

I’m Michelle Gallagher, a Senior Python Developer at Lumenalta based in New York, United States. I have over nine years of experience in the field of Python development, machine learning, and artificial intelligence. My expertise lies in Python and its extensive ecosystem of libraries and frameworks. Throughout my career, I’ve had the pleasure of working on a variety of projects that have leveraged my skills in Python and machine learning. Read more…