Python while Loop

Python3 循环语句Python3 Loop Statements


whileis a conditional loop statement in Python; as long as the condition is True, it will continue to execute the loop body.

andforDifferent,whileloop is more suitable for scenarios where the number of iterations is uncertain and you need to exit based on conditions.

Word Explanation: whileIt means "while...", indicating continuous execution while the condition is true.


Basic Syntax and Parameters

Syntax Format

while 条件:
    # 循环体(必须缩进)
    语句1
    语句2
    ...
else:
    # 可选,当循环“正常结束”时执行
    语句1
    语句2
    ...

Syntax Description

  • Condition: The conditional expression evaluated before each loop iteration.
  • Execution Logic: When it is True, execute the loop body, then re-evaluate the condition.
  • Exit Condition: When the condition is False, exit the loop.

else Clause

  • Optional: Similar to for, while can also have an else.
  • Execution Timing: It executes when the condition becomes False (normal exit).


Examples

Example 1: Basic Usage

Examples

# Basic while loop
count = 0

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

print("Loop ended")

Expected output:

0
1
2
3
4
循环结束

Code explanation:

  1. Continue looping while count < 5.
  2. Each iteration increments count by 1.
  3. When count = 5, the condition becomes False and the loop exits.

Example 2: User Input Validation

Examples

# Simulate user input validation
# Note: In actual operation, input() will wait for user input

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

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

print("Congratulations, you guessed it!")

Expected output:

请输入数字 (7): 5
太小了
请输入数字 (7): 9
太大了
请输入数字 (7): 7
恭喜,猜对了!

The while loop is often used in scenarios that require repetition until a condition is met.

Example 3: Calculating Factorial

Examples

# Calculate factorial
n = 5
result = 1

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

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

# Accumulative summation
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.

Example 4: while-else Structure

Examples

# while-else
count = 0

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

print("---")

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

Expected output:

0
1
2
循环正常结束
---
0
1
2

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

Example 5: Infinite Loop and Exit

Examples

# Infinite loops need to be used carefully
# The example below uses break to exit

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

    choice = input("Please choose: ")

    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 loop
    else:
        print("Invalid choice")

print("Program ended")

Infinite loops combined with break can implement complex control flows.

Expected output:

=== 菜单 ===
1. 查看余额
2. 存款
3. 取款
4. 退出
请选择: 1
余额: 1000元

=== 菜单 ===
1. 查看余额
2. 存款
3. 取款
4. 退出
请选择: 

Python3 循环语句Python3 Loop Statements

Other Extensions