Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python while Loop

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 keeps executing.

The difference between for in Vue 2,while The loop is better suited to scenarios where the number of iterations is uncertain and the exit depends on a condition.

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


Basic syntax and parameters

Syntax format


while 条件:
    # Loop body (must be indented)
    语句1
    语句2
    ...
else:
    # Optional, executes when the loop "normally finishes"
    语句1
    语句2
    ...

Syntax Description

else clause


Example

Example 1: basic usage

Example

A basic while loop

count

=

0

while

count

<

5

:

   

print

(

count

)

    count +

=

1

print

(

"Loop ended"

)

Expected output:

0
1
2
3
4
循环结束

Code analysis:

  1. When count < is less than 5, keep looping.
  2. Each iteration increases count by 1.
  3. When count = 5, the condition is False and the loop exits.

Example 2: user input validation

Example

Simulate user input validation

Note: when actually run, input() waits for user input

Simple example: guessing a 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 large"

)

print

(

"Congratulations, you guessed it!"

)

Expected output:

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

while loops are often used in scenarios that need to repeat until a condition is met.

Example 3: calculating a factorial

Example

Calculate the factorial

n

=

5

result

=

1

while

n

0

:

    result *

=

n

    n -

=

1

print

(

f

"5! = {result}"

)

 

Output: 5! = 120

Accumulated 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 computation, be careful to avoid infinite loops.

Example 4: the while-else structure

Example

while-else

count

=

0

while

count

<

3

:

   

print

(

count

)

    count +

=

1

else

:

   

print

(

"The loop ended normally"

)

print

(

"---"

)

else is not executed when break is used

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

In while-else, the else is not executed when terminated by break.

Example 5: infinite loops and exiting

Example

Infinite loops need to be used with care

The following example uses break to exit

Simulate a menu system

while

True

:

   

print

(

"=== Menu ==="

)

   

print

(

"1. Check 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 the loop

   

else

:

       

print

(

"Invalid choice"

)

print

(

"Program ends"

)

Combining infinite loops with break enables complex control flows.

Expected output:


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

=== 菜单 ===
1. 查看余额
2. 存款
3. 取款
4. 退出
Please select:

Python3 Loop Statements Python3 loop statements