东尧

循环就是当条件满足的时候,就会重复的执行某些事情,直到条件不满足退出。python中的循环语句主要有while循环和for循环两种。本文主要讲while循环,下一篇文章将继续for循环的讲解。

1

while 循环语句结构

while 条件表达式:

循环体语句块

while循环中,当条件表达式为真时,就会重复的执行循环体内的语句块,直到条件为假才退出。

示例代码:

# 计数循环
count = 1
while count
print ("hello, I am %d loop" % count)
count += 1

结果:

hello, I am 1 loop

hello, I am 2 loop

hello, I am 3 loop

hello, I am 4 loop

hello, I am 5 loop

hello, I am 6 loop

hello, I am 7 loop

hello, I am 8 loop

hello, I am 9 loop

hello, I am 10 loop

死循环:

# 死循环(无限循环)
while True:
print ("dead loop")

一般情况下,很少使用死循环,除非要求程序一直是执行的,比如持续的网络请求的时候。一般死循环里面都会结合条件判断语句,用以在某些适当的情况下退出循环体。

2

使用break语句跳出循环体

while True:
name = input("请输入你的名字(输入Q可退出程序):")
if name == "Q":
break
print ("你的名字是:%s" % name, "欢迎你的到来。")

示例结果:

请输入你的名字(输入Q可退出程序):东尧

你的名字是:东尧 欢迎你的到来。

请输入你的名字(输入Q可退出程序):你好

你的名字是:你好 欢迎你的到来。

请输入你的名字(输入Q可退出程序):Q

break语句是跳出当前语句所在的循环体,如果有循环嵌套的且break是在内层循环的,那么只会跳出内层循环,不会跳出外层循环。

outer = 3
inner = 5
while outer > 0:
while inner > 0:
if inner
break
print("I am inner loop",inner)
inner -= 1
print("I am outer loop", outer)
outer -= 1

结果:

I am inner loop 5

I am inner loop 4

I am inner loop 3

I am outer loop 3

I am outer loop 2

I am outer loop 1

3

使用continue语句跳出当次循环

continue 只是跳出当次循环,并不是跳出整个循环体。中断当次循环,执行下次循环。对于嵌套的循环,continue跳过的也是它所在的那层循环的当次循环,与break是相似的。

count = 10
while count > 0:
count -= 1
if count == 5:
continue
print('loop',count)

结果:

count = 10

while count > 0:

if count == 5:

continue

print('loop',count)

count -= 1

结果:

为什么上面两个案例因为count -= 1的位置不同(一个在开始、一个在结尾),结果会有这么大的差异呢?那是因为第二个案例中,在执行到count = 5的时候符合条件判断式,触发了continue,因此直接跳过了后面的代码,也就不会在执行count -= 1了,也就是说count维持在了数值“5”这个状态。

4

神奇的else

在其他的语言中,循环是没有else搭配的,但是python却出了这么个东西。当循环体是正常的结束的时候(没有break中断的)那么就会执行else语句的部分。

count = 0
while count
print("hello", count)
count += 1
else:
print("while loop done well")

关于Python中while循环语句的用法总结到这就基本结束了,这篇文章对于大家学习或者使用Python还是具有一定的参考借鉴价值的,希望对大家能有所帮助