PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Python while loop

Python while loop

Updated on: November 28, 2026 | 5 Comments

In this tutorial, you’ll learn what a while loop is in Python and how to use it. A while loop repeats a block of code as long as a condition stays true. It is the right choice when you don’t know in advance how many times the code needs to run.

By the end of this article, you’ll know how to write while loops, avoid infinite loops, control them with break, continue, pass, and else, and use common patterns such as input validation and while True loops.

Also, Solve:

  • Python loop Exercise
  • Python loop Quiz

Table of contents

  • What is a while loop in Python?
    • Syntax of a while loop
    • Example of a while loop in Python
    • Flowchart of a while loop
  • Why and when to use a while loop in Python
    • while loop vs for loop
  • Infinite while loop
    • while True with break
    • Emulating a do-while loop
  • If-else in a while loop
  • Transfer statements in a while loop
    • Break statement
    • Continue statement
    • Pass statement
  • Nested while loops
    • for loop inside a while loop
  • Else statement in a while loop
  • Reverse while loop
  • Iterate a string using a while loop
  • Iterate a list using a while loop
  • while loop with the walrus operator
  • Common mistakes and best practices
  • Summary
  • Next Steps

What is a while loop in Python?

In Python, the while loop statement repeatedly executes a block of code as long as a given condition is true.

count = 1
# condition: run the loop while count is less than 3
while count < 3:
    print(count)
    count = count + 1Code language: Python (python)

In simple words, a while loop lets your program repeat a set of operations while a condition is true. As soon as the condition becomes false, the loop stops, and Python runs the first statement after the loop.

The while loop is one of Python’s control flow statements, and understanding it is an essential part of learning the basics of Python.

Use a while loop when the number of iterations is not known beforehand. For example, if you ask a user to guess your lucky number between 1 and 10, you don’t know how many attempts they will need. A while loop can keep asking until they get it right.

  • Indefinite iteration: The number of iterations is unknown. For example, asking the user to guess a lucky number. It could take 1 attempt, 20, or more. In such cases, use a while loop.
  • Definite iteration: The number of iterations is fixed. For example, printing the multiplication table of 2 needs exactly 10 iterations. In such cases, use a for loop.
while loop in Python
while loop in Python

Syntax of a while loop

while condition:
    # block of statement(s)Code language: Python (python)
  • The while statement first checks the condition. The condition is any expression that Python can evaluate as True or False.
  • If the condition is True, Python runs the indented statements inside the loop body.
  • After the body finishes, Python checks the condition again. This repeats until the condition becomes False.
  • If the condition is False the very first time, the loop body never runs at all.
  • Don’t forget the colon (:) after the condition, and indent the loop body (usually by 4 spaces).

Example of a while loop in Python

Let’s start with a simple example.

Example 1: Print numbers less than 5

count = 1
# run the loop while count is less than 5
while count < 5:
    print(count)
    count = count + 1Code language: Python (python)

Output:

1
2
3
4

In this example, the loop runs as long as the count variable is less than 5. In each iteration, we increase count by 1. When count reaches 5, the condition becomes false and the loop stops.

Note: If you forget to increase count in the example above, the condition will always be true and the loop will run forever.

Example 2: Count how many times a number must be divided by 3 until it is less than or equal to 10

Here, the number of iterations depends on the starting number, so we can’t know it in advance. This is exactly the kind of problem a while loop is made for.

count = 0
number = 180
while number > 10:
    # divide number by 3
    number = number / 3
    # increase count
    count = count + 1
print('Total iterations required:', count)Code language: Python (python)

Output:

Total iterations required: 3

The number goes from 180 to 60, then 20, then about 6.67. After the third division, it is no longer greater than 10, so the loop stops.

Flowchart of a while loop

while loop flowchart
while loop flowchart

Why and when to use a while loop in Python

Here are the main reasons to choose a while loop:

  • Automate and repeat tasks: A while loop runs a block of code again and again until its condition is no longer met, so you can automate repetitive work efficiently.
  • Indefinite iteration: The loop runs as many times as needed to finish the task. When you don’t know the number of iterations before the program runs, use a while loop instead of a for loop.
  • Less repetitive code: Instead of writing the same statements many times, you write them once inside the loop body. This keeps the code short and easy to maintain.
  • Wait for an event: A while loop can keep running until something happens, such as the user typing “quit”, a file becoming available, or a game ending.

Example: Make sure the user enters valid input

In this example, we want the user to enter a number between 100 and 500. We keep asking until they enter a number within that range.

number = int(input('Enter any number between 100 and 500: '))
# keep asking while the number is outside the range
while number < 100 or number > 500:
    print('Incorrect number. Please try again.')
    number = int(input('Enter a number between 100 and 500: '))

print("The given number is correct:", number)Code language: Python (python)

Output:

Enter any number between 100 and 500: 700
Incorrect number. Please try again.
Enter a number between 100 and 500: 98
Incorrect number. Please try again.
Enter a number between 100 and 500: 300
The given number is correct: 300

while loop vs for loop

  • for loop: Loops over the items of a sequence or a range(). Use it when you know how many times to repeat, or when you want to process every item in a collection.
  • while loop: Loops as long as a condition is true. Use it when the number of repetitions depends on something that changes while the program runs, such as user input or a calculation result.
  • In a for loop, Python moves to the next item for you. In a while loop, you are responsible for changing something so that the condition eventually becomes false.

Infinite while loop

If the condition of a while loop never becomes false, the loop runs forever. This is called an infinite loop.

# Infinite while loop
while True:
    print('Hello')Code language: Python (python)

An accidental infinite loop is a bug, usually caused by forgetting to update the loop variable. If your program gets stuck, press Ctrl + C in the terminal to stop it (this raises a KeyboardInterrupt).

while True with break

Infinite loops can also be intentional. A very common pattern is while True combined with a break statement that exits the loop when a certain condition is met. Programs such as menus, chat bots, and games often work this way.

while True:
    text = input("Type something (or 'quit' to exit): ")
    if text == "quit":
        print("Goodbye!")
        break
    print("You typed:", text)Code language: Python (python)

Output:

Type something (or 'quit' to exit): hello
You typed: hello
Type something (or 'quit' to exit): python
You typed: python
Type something (or 'quit' to exit): quit
Goodbye!

Emulating a do-while loop

Some languages have a do-while loop, which always runs its body at least once and checks the condition at the end. Python doesn’t have a do-while loop, but you can get the same behavior with while True and a break at the bottom of the loop.

x = 10
while True:
    print("x is", x)
    x = x + 1
    # condition is checked at the end
    if x > 3:
        breakCode language: Python (python)

Output:

x is 10

Even though x is already greater than 3, the body runs once before the condition is checked.

If-else in a while loop

If-else statements let you run different blocks of code depending on whether a condition is true or false.

Use an if-else statement inside a loop when you want to do different things in different iterations. If the condition is True, the statements inside the if block run. Otherwise, the else block runs.

Syntax of an if-else statement

if condition:
    block of statements
else:
    block of statementsCode language: Python (python)

Example: Print even and odd numbers from the entered number down to 1

n = int(input('Please enter a number: '))
while n > 0:
    # check even and odd
    if n % 2 == 0:
        print(n, 'is an even number')
    else:
        print(n, 'is an odd number')
    # decrease number by 1 in each iteration
    n = n - 1Code language: Python (python)

Output:

Please enter a number: 7
7 is an odd number
6 is an even number
5 is an odd number
4 is an even number
3 is an odd number
2 is an even number
1 is an odd number

Transfer statements in a while loop

Loop control statements change the normal flow of a loop. Use them when you want to exit a loop early or skip part of it based on a condition. They are also known as transfer statements.

Python has three loop control statements: break, continue, and pass.

Break statement

The break statement ends the loop that contains it immediately. If you use break inside a nested loop (a loop inside another loop), it ends only the innermost loop.

Example: Display each character of a string and stop the loop when a digit is found

name = 'Jessa29Roy'
size = len(name)
i = 0
# iterate until the last character
while i < size:
    # stop the loop if the current character is a digit
    if name[i].isdecimal():
        break
    # print current character
    print(name[i], end=' ')
    i = i + 1Code language: Python (python)

Output:

J e s s a 

Continue statement

The continue statement skips the rest of the loop body for the current iteration and jumps back to the condition check. Unlike break, it doesn’t end the loop.

Example: Display only the letters of a string

In this example, we print only the letters and skip all digits and special symbols. Notice that we increase i before the continue statement. If the increment came after continue, it would be skipped and the loop would never end.

name = 'Jessa29Roy'
size = len(name)
i = 0
while i < size:
    char = name[i]
    i = i + 1
    # skip the rest of the body if the character is not a letter
    if not char.isalpha():
        continue
    print(char, end=' ')Code language: Python (python)

Output:

J e s s a R o y 

Pass statement

The pass statement is a null statement: nothing happens when it runs. Python doesn’t allow an empty block, so pass works as a placeholder when the syntax needs a statement but you have nothing to write yet. It is also commonly used in empty functions and classes.

n = 4
while n > 0:
    n = n - 1
    # TODO: add more logic here later
    passCode language: Python (python)

Nested while loops

A while loop inside another while loop is called a nested loop.

For each iteration of the outer loop, the inner loop runs through all of its iterations. So the total number of iterations is the outer loop’s iterations multiplied by the inner loop’s iterations.

while expression:
    while expression:
        statement(s) of inner loop
    statement(s) of outer loopCode language: Python (python)

Example: Use a nested while loop to print a pattern

* 
* * 
* * * 
* * * *
i = 1
# outer while loop
# 4 rows in pattern
while i < 5:
    j = 0
    # nested while loop
    while j < i:
        print('*', end=' ')
        j = j + 1
    # end of nested while loop
    # new line after each row
    print('')
    i = i + 1Code language: Python (python)

Note that the inner counter j is reset to 0 at the start of every outer iteration. Forgetting this reset is a common mistake with nested while loops.

for loop inside a while loop

You can also use a for loop inside a while loop. Here is the same pattern written with an inner for loop, which removes the need for the j counter:

i = 1
# outer while loop
while i < 5:
    # nested for loop
    for j in range(1, i + 1):
        print("*", end=" ")
    print('')
    i = i + 1Code language: Python (python)

Else statement in a while loop

A while loop can have an optional else block. The else block runs once, when the loop condition becomes false, that is, when the loop ends normally.

The else block does not run when the loop is stopped by a break statement (or by an exception or a return).

Example 1: Use a while loop to print numbers from 1 to 5

i = 1
while i <= 5:
    print(i)
    i = i + 1
else:
    print("Done. while loop executed normally")Code language: Python (python)

Output:

1
2
3
4
5
Done. while loop executed normally

Example 2: Else block with a break statement

Here the loop is stopped by break when i equals 3, so the else block is skipped.

i = 1
while i <= 5:
    print(i)
    if i == 3:
        break
    i = i + 1
else:
    print("Done. while loop executed normally")Code language: Python (python)

Output:

1
2
3

Example 3: A practical use of while-else: searching for an item

Find the first multiple of 5 in a list. If none is found, the else block reports it, with no extra flag variable needed.

numbers = [4, 9, 15, 22]
i = 0
while i < len(numbers):
    if numbers[i] % 5 == 0:
        print("First multiple of 5:", numbers[i])
        break
    i = i + 1
else:
    print("No multiple of 5 found")Code language: Python (python)

Output:

First multiple of 5: 15

Reverse while loop

A reverse loop iterates backward. Common examples are:

  • Displaying numbers from 10 down to 1
  • Reversing a string or a list

Example: Use a reverse while loop to display numbers from 10 to 1

# reverse while loop
i = 10
while i >= 1:
    print(i, end=' ')
    i = i - 1Code language: Python (python)

Output:

10 9 8 7 6 5 4 3 2 1 

Iterate a string using a while loop

You can loop through a string with a while loop by using an index variable that goes from 0 to len(string) - 1.

Example 1: Iterate a string letter by letter

name = "Jessa"
i = 0
while i < len(name):
    print(name[i])
    i = i + 1Code language: Python (python)

Output:

J
e
s
s
a

Example 2: Iterate a string in reverse order

name = "Jessa"
i = len(name) - 1
while i >= 0:
    print(name[i], end=' ')
    i = i - 1Code language: Python (python)

Output:

a s s e J 

Iterate a list using a while loop

A Python list is an ordered sequence of items. Each item has an index number, starting from 0. Lists are written inside square brackets []. Here are some examples of lists:

numbers = [1, 2, 4, 6, 7]
names = ["Messi", "Ronaldo", "Neymar"]Code language: Python (python)

Example 1: Use a while loop to iterate over a list

numbers = [1, 2, 4, 5, 7]
size = len(numbers)
i = 0
while i < size:
    print(numbers[i])
    i = i + 1Code language: Python (python)

Output:

1
2
4
5
7

Example 2: Process a list until it is empty

An empty list is treated as False in a condition, so while tasks: keeps running as long as the list has items. The pop() method removes and returns the last item, so the list shrinks in each iteration.

tasks = ["email", "code", "review"]
while tasks:
    task = tasks.pop()
    print("Doing:", task)
print("Tasks left:", tasks)Code language: Python (python)

Output:

Doing: review
Doing: code
Doing: email
Tasks left: []

Tip: To simply visit every item of a list, a for loop is shorter and safer. Use a while loop when the list changes inside the loop or when you need to stop based on a condition.

while loop with the walrus operator

Python 3.8 introduced the assignment expression operator :=, nicknamed the walrus operator. It lets you assign a value and test it in the same while condition, which avoids repeating the same line before and inside the loop.

# keep reading input until the user presses Enter on an empty line
while (line := input("Enter text: ")) != "":
    print("Read:", line)Code language: Python (python)

Output:

Enter text: a
Read: a
Enter text: b
Read: b
Enter text: 

Common mistakes and best practices

  • Forgetting to update the loop variable: This is the most common cause of infinite loops. Make sure something in the loop body moves the condition toward False.
  • Skipping the update with continue: If the increment comes after a continue statement, it may never run. Update the counter before continue.
  • Off-by-one errors: Check whether you need < or <=. For example, while i < 5 stops at 4, while while i <= 5 includes 5.
  • Not resetting the inner counter: In nested while loops, reset the inner counter at the start of each outer iteration.
  • Using a while loop where a for loop is clearer: To visit every item in a list or repeat something a fixed number of times, a for loop is shorter and less error-prone.
  • Floating-point conditions: Avoid conditions like while x != 1.0 with floats. Rounding errors may stop x from ever exactly matching. Use < or > instead.

Summary

  • A while loop repeats a block of code as long as its condition is True.
  • Use it when you don’t know in advance how many iterations you need. Use a for loop when you do.
  • Always change something inside the loop so the condition eventually becomes False, or the loop will run forever.
  • while True with break is a common pattern for menus, input loops, and do-while behavior.
  • break exits the loop, continue skips to the next iteration, and pass does nothing.
  • The optional else block runs only when the loop ends without break.
  • The walrus operator := lets you assign and test a value in the loop condition.

Next Steps

Practice what you’ve learned, and continue with the related tutorials on for loops, nested loops, and break, continue, and pass.

Solve:

  • Python loop Exercise
  • Python loop Quiz

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes
In: Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com