Python编程while语句的基本形式、执行流程及相关命令用法

[id_[id_981787[id_186468918[id_1799220361]]41]6[id_1044258196]9886450]

Python编程while语句的基本形式、执行流程及相关命令用法

while 判断条件:
    执行语句……

执行指令可以是单一命令或一系列指令。评估标准可以是各式各样的表达式,只要是非零数值或非空数据,都被视为有效。

当判断条件假false时,循环结束。

执行流程图如下:

实例:

#!/usr/bin/python
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!

在while语句中,存在两个关键指令,即continue和break,它们均能实现跳出循环的功能。其中,continue用于跳过当前循环的剩余部分,而break则用于直接退出整个循环。此外,所谓的“判断条件”也可以是一个固定值,确保循环必然持续进行。具体的使用方法如下:

# continue 和 break 用法
i = 1
while i < 10:   
    i += 1
    if i%2 > 0:     # 非双数时跳过输出
        continue
    print i         # 输出双数2、4、6、8、10
i = 1
while 1:            # 循环条件为1必定成立
    print i         # 输出1~10
    i += 1
    if i > 10:     # 当i大于10时跳出循环
        break

无限循环

若条件判断始终成立,则循环操作将持续不断进行,例如:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
var = 1
while var == 1 :  # 该条件永远为true,循环将无限执行下去
   num = raw_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 between :Traceback (most recent call last):
  File "test.py", line 5, in 
    num = raw_input("Enter a number :")
KeyboardInterrupt

注意:以上的无限循环你可以使用 CTRL+C 来中断循环。

循环使用 else 语句

在Python编程语言中,"for...else"结构具有特定含义,其中"for"部分内的代码与常规的"for"循环语句相同,而"else"部分内的代码则会在循环正常完成(即未通过"break"语句提前终止)时执行。类似地,"while...else"结构也遵循相同的规则。

#!/usr/bin/python
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

简单语句组

若条件语句的格式与if类似,那么在while循环体内仅包含一个指令时,可以将该指令与while循环一同置于同一行,例如:

#!/usr/bin/python
flag = 1
while (flag): print 'Given flag is really true!'
print "Good bye!"

注意:以上的无限循环你可以使用 CTRL+C 来中断循环。

本篇内容遵循「CC BY-SA 4.0 CN」授权协议,源自网络,仅用于学术研讨与信息交流,资料版权归属原作者。若涉及作品、版权等事宜,烦请通过「我们」的联系方式进行沟通解决。

你可能想看:
« 上一篇
下一篇 »

相关推荐

python爬虫教程PDF,Python爬虫书PDF

2026年09月02日

31阅读

外国教程python,python编程教学视频

2026年09月02日

25阅读

python简明教程沈洁元,python详细基础教程

2026年09月02日

21阅读

python库包教程,python 包

2026年09月02日

27阅读

python教程大全集,python教程600集

2026年09月02日

26阅读

python入门教程完整版,python零基础入门全套教程视频

2026年09月02日

22阅读