Python while循环

Python 编程语言中的while循环语句只要给定条件为真,就会重复执行目标语句

语法

Python 编程语言中while循环的语法是:

while 条件:
    # 循环体内的代码

循环体内的代码将一直执行,直到条件变为 False 或者通过 break 语句显式地跳出循环。在每次循环迭代时,都会检查条件的真假,如果条件为真,则继续执行循环体内的代码。

流程图

Python while循环

这里,while 循环的一个关键点是该循环可能永远不会运行。当条件测试结果为假时,将跳过循环体并执行 while 循环后的第一条语句。

例子

#!/usr/bin/python3

count = 0
while (count < 9):
   print ('The count is:', count)
   count = count + 1

print ("Good bye!")

输出:

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

这里的块由 print 和increment 语句组成,重复执行,直到 count 不再小于 9。每次迭代,都会显示索引 count 的当前值,然后加 1。

无限循环

如果条件永远不会变为 FALSE,则循环将变为无限循环。使用 while 循环时必须小心,因为此条件可能永远不会解析为 FALSE 值。这会导致一个永远不会结束的循环。这样的循环称为无限循环。

无限循环在客户端/服务器编程中可能很有用,其中服务器需要连续运行,以便客户端程序可以在需要时与其进行通信。

例子

#!/usr/bin/python3

var = 1
while var == 1 :  # This constructs an infinite loop
   num = int(input("Enter a number  :"))
   print ("You entered: ", num)

print ("Good bye!")

输出:

Enter a number  :20
You entered:  20
Enter a number  :29
You entered:  29
Enter a number  :3
You entered:  3
Enter a number  :11
You entered:  11
Enter a number  :22
You entered:  22
Enter a number  :Traceback (most recent call last):
   File "examples\test.py", line 5, in 
      num = int(input("Enter a number  :"))
KeyboardInterrupt

上面的例子进入了无限循环,需要使用CTRL+C退出程序。

将 else 语句与循环一起使用

Python 支持将else语句与循环语句关联。

  • 如果else语句与for循环一起使用,则当循环耗尽列表的迭代后,将执行else语句。
  • 如果else语句与while循环一起使用,则当条件为 false 时执行else语句。

下面的示例说明了 else 语句与 while 语句的组合,只要该数字小于 5,就打印数字,否则执行 else 语句。

例子

#!/usr/bin/python3

count = 0
while count < 5:
   print (count, " is  less than 5")
   count = count + 1
else:
   print (count, " is not less than 5")

输出:

0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

单行 while子句

if语句语法类似,如果您的while子句仅包含单个语句,则它可以与 while 标头放在同一行。

例子

以下是单行 while子句的语法和示例:

#!/usr/bin/python3

flag = 1
while (flag): print ('Given flag is really true!')
print ("Good bye!")

上面的例子进入了无限循环,需要按CTRL+C键退出。

带有用户输入的Python while循环

a = int(input('Enter a number (-1 to quit): '))

# 进入一个循环,直到用户输入 -1 为止
while a != -1:
    a = int(input('Enter a number (-1 to quit): '))

# 当用户输入 -1 后,循环结束

输出:

Python while循环

解释:

  • 首先,它要求用户输入一个数字。如果用户输入-1则循环将不会执行
  • 用户输入 6,循环体执行并再次要求输入
  • 这里用户可以输入多次,直到输入-1停止循环
  • 用户可以决定输入多少次