python:第二十七章:while循环

一,while语句:
1,语法:
while 条件表达式:
# 循环体
当条件表达式的返回值为真时,则执行循环体中的语句,
执行完毕后,重新判断条件表达式的返回值,
如果表达式返回的结果为假,则退出循环体
2,流程图:

说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/11/17/python-di-er-shi-liu-zhang-while-xun-huan/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,例子:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
# 打印从1到10n = 1while n <= 10: print(n, end=" ") n += 1# 打印一个空行print()# 计算从1加到100的和n = 1sumRes = 0while n <= 100: sumRes += n n += 1print("1到100的和为:", sumRes) |
运行结果:
1 2 3 4 5 6 7 8 9 10
1到100的和为: 5050
说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/11/17/python-di-er-shi-liu-zhang-while-xun-huan/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
三,遍历列表
|
1
2
3
4
5
6
7
8
|
# 遍历列表# len函数用来得到列表的长度staffs = ["擎天柱", "补天士", "热破", "通天晓"]length = len(staffs)i = 0while i < length: print(staffs[i]) i += 1 |
运行结果:
擎天柱
补天士
热破
通天晓
浙公网安备 33010602011771号