Python while循环教程
Python 的 while 循环跟 if 和 for 语句类似,都是使用 : 做为分割符,要执行的代码块都是使用相同的缩进形式。
Python while循环详解
语法
while cond:
# do something
说明
当 cond 条件为真时,一直执行缩进里面的代码块,直到 cond 条件为假,循环结束。
案例
while循环数字
使用 while 循环,遍历数字
print("嗨客网(www.haicoder.net)")
# 使用 while循环,遍历数字
num = 0
while num < 3:
print('Num =', num)
num = num + 1
程序运行后,控制台输出如下:
首先,我们定义了一个
while求和
使用 while 循环,求和
print("嗨客网(www.haicoder.net)")
# 使用 while循环,求和
num = 0
sum = 0
while num <= 100:
sum += num
num += 1
print("Sum =", sum)
程序运行后,控制台输出如下:
首先,我们定义了一个整型类型变量 num 和 sum,并且都赋值为 0,接着使用 while 循环来判断变量 num 是否小于等于 100,如果成立,则一直将当前 sum 的值加上 num,并且每次执行后都将 num 变量加 1。
整个 while 循环执行完毕后,执行 print 的代码块,输出 Sum 的值。因为 print 语句不是在 while 循环的缩进代码块里面,而是跟 while 是平级的,因此 print 是 while 循环执行完毕才会执行的。
while循环列表
使用 while 循环,遍历列表
print("嗨客网(www.haicoder.net)")
# 使用 while循环,遍历列表
ls = ["Hello", "HaiCoder"]
i = 0
while i < len(ls):
print(ls[i])
i += 1
print("Over")
程序运行后,控制台输出如下:
首先,我们定义了一个
每次遍历后都使用 print 函数打印当前的遍历的值并且将变量 i 的值加 1。
while循环元祖
使用 while循环,遍历元祖
print("嗨客网(www.haicoder.net)")
# 使用 while循环,遍历元祖
tup = ("Hello", "HaiCoder")
i = 0
while i < len(tup):
print(tup[i])
i += 1
print("Over")
程序运行后,控制台输出如下:
首先,我们定义了一个
每次遍历后都使用 print 函数打印当前的遍历的值并且将变量 i 的值加 1。
Python while循环总结
Python 的 while 循环跟 if 条件判断类似,都是在特定条件满足的情况下,执行相对应的代码,不过,while 循环是只要条件满足,会一直执行缩进里面的代码块,这点又类似于 for 循环 。Python while 循环语法:
while cond:
# do something