python所有for循环语句都可以用while改写_Python while循环

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

程序运行后,控制台输出如下:

27_python while循环.png

首先,我们定义了一个

while求和

使用 while 循环,求和

print("嗨客网(www.haicoder.net)")

# 使用 while循环,求和

num = 0

sum = 0

while num <= 100:

sum += num

num += 1

print("Sum =", sum)

程序运行后,控制台输出如下:

28_python while循环.png

首先,我们定义了一个整型类型变量 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")

程序运行后,控制台输出如下:

29_python while循环.png

首先,我们定义了一个

每次遍历后都使用 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")

程序运行后,控制台输出如下:

30_python while循环.png

首先,我们定义了一个

每次遍历后都使用 print 函数打印当前的遍历的值并且将变量 i 的值加 1。

Python while循环总结

Python 的 while 循环跟 if 条件判断类似,都是在特定条件满足的情况下,执行相对应的代码,不过,while 循环是只要条件满足,会一直执行缩进里面的代码块,这点又类似于 for 循环 。Python while 循环语法:

while cond:

# do something

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值