Skip to content

Python while Loop

Python3 Loop Statements Python3 Loop Statements


while is a conditional loop statement in Python. As long as the condition is True, the loop body continues to execute.

Unlike for, the while loop is more suitable for scenarios where the number of iterations is uncertain and where you need to exit based on a condition.

Word Meaning: while means “as long as”, indicating that execution continues as long as the condition is true.


while condition:
    # Loop body (must be indented)
    statement1
    statement2
    ...
else:
    # Optional, executed when the loop ends "normally"
    statement1
    statement2
    ...
  • condition: The conditional expression evaluated before each loop iteration begins.
  • Execution Logic: When True, the loop body executes, then the condition is re-evaluated.
  • Exit Condition: The loop exits when the condition becomes False.
  • Optional: Similar to for, while can also have an else.
  • Execution Timing: Executed when the condition becomes False (normal exit).


# Basic while loop
count = 0

while count < 5:
    print(count)
    count += 1

print("Loop ended")

Expected Output:

0
1
2
3
4
Loop ended

Code Explanation:

  1. The loop continues while count < 5.
  2. count increases by 1 each iteration.
  3. When count = 5, the condition is False, and the loop exits.
# Simulate user input validation
# Note: When actually running, input() waits for user input

# Simple example: guess the number
secret = 7
guess = 0

while guess != secret:
    guess = int(input("Enter a number (7): "))
    if guess < secret:
        print("Too small")
    elif guess > secret:
        print("Too large")

print("Congratulations, you guessed correctly!")

Expected Output:

Enter a number (7): 5
Too small
Enter a number (7): 9
Too large
Enter a number (7): 7
Congratulations, you guessed correctly!

The while loop is commonly used in scenarios requiring repetition until a condition is met.

# Calculate factorial
n = 5
result = 1

while n > 0:
    result *= n
    n -= 1

print(f"5! = {result}")  # Output: 5! = 120

# Cumulative sum
total = 0
i = 1
while i <= 100:
    total += i
    i += 1
print(f"1+2+...+100 = {total}")  # Output: 5050

Expected Output:

5! = 120
1+2+...+100 = 5050

When using while loops for numerical calculations, be careful to avoid infinite loops.

# while-else
count = 0

while count < 3:
    print(count)
    count += 1
else:
    print("Loop ended normally")

print("---")

# else does not execute when break is used
count = 0
while count < 5:
    if count == 3:
        break
    print(count)
    count += 1
else:
    print("This line will not print")

Expected Output:

0
1
2
Loop ended normally
---
0
1
2

The else clause of while-else does not execute when the loop is terminated by break.

# Infinite loops should be used with caution
# The following example uses break to exit

# Simulate a menu system
while True:
    print("\n=== Menu ===")
    print("1. Check Balance")
    print("2. Deposit")
    print("3. Withdraw")
    print("4. Exit")

    choice = input("Please select: ")

    if choice == "1":
        print("Balance: 1000 yuan")
    elif choice == "2":
        print("Deposit function")
    elif choice == "3":
        print("Withdrawal function")
    elif choice == "4":
        print("Thank you for using")
        break  # Exit the loop
    else:
        print("Invalid selection")

print("Program ended")

Infinite loops combined with break can implement complex control flows.

Expected Output:

=== Menu ===
1. Check Balance
2. Deposit
3. Withdraw
4. Exit
Please select: 1
Balance: 1000 yuan

=== Menu ===
1. Check Balance
2. Deposit
3. Withdraw
4. Exit
Please select: 

Python3 Loop Statements Python3 Loop Statements