python中的语句是什么意思_python语句意思

本文详细介绍了Python中的while循环语句,包括基本结构、continue和break的使用、常数值判断的循环以及避免无限循环的方法。通过实例演示了如何控制程序的重复执行,以及如何结合else语句处理循环结束条件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2018-06-09 回答

python while循环语句

python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其基本形式为:

while 判断条件:

执行语句……

执行语句可以是单个语句或语句块。判断条件可以是任何表达式,任何非零、或非空(null)的值均为true。

当判断条件假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

无限循环

如果条件判断语句永远为 true,循环将会无限的执行下去,如下实例:

#coding=utf-8

#!/usr/bin/python

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 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 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 来中断循环。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值