4.2_控制流2while__range语句.docx
来源:互联网 发布:javaweb js 跨域 编辑:程序博客网 时间:2024/06/07 07:15
4.2_控制流2while__range语句.docx
1. while语句
Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其基本形式为:
while判断条件:执行语句……
执行语句可以是单个语句或语句块。判断条件可以是任何表达式,任何非零、或非空(null)的值均为true。
当判断条件假false时,循环结束。
执行流程图如下:
python_while_loop
Gif 演示 Python while 语句执行过程
实例
#!/usr/bin/pythoncount =0while(count <9):print'The count is:',countcount =count + 1print"Good bye!"
运行实例 »
以上代码执行输出结果:
The countis:0The countis:1The countis:2The countis:3The countis:4The countis:5The countis:6The countis:7The countis:8Good bye!
while 语句时还有另外两个重要的命令 continue,break 来跳过循环,continue 用于跳过该次循环,break 则是用于退出循环,此外"判断条件"还可以是个常值,表示循环必定成立,具体用法如下:
设置 一直到 用户把 66 猜出来
#while example
number = 66
guess_flag = False
while guess_flag == False:
guess = int(input('Enter an integer : '))
if guess == number:
# New block starts here
guess_flag = True
# New block ends here
elif guess < number:
# Another block
print('No, the number is higher than that, keep guessing')
# You can do whatever you want in a block ...
else:
print('No, the number is a lower than that, keep guessing')
# you must have guessed > number to reach here
print('Bingo! you guessed it right.')
print('(but you do not win any prizes!)')
print('Done')
2. range语句
Code:
#For example
number = 59
num_chances = 3
print("you have only 3 chances to guess")
for i in range(1, num_chances + 1):
print("chance " + str(i))
guess = int(input('Enter an integer : '))
if guess == number:
# New block starts here
print('Bingo! you guessed it right.')
print('(but you do not win any prizes!)')
break
# New block ends here
elif guess < number:
# Another block
print('No, the number is higher than that, keep guessing, you have ' + str(num_chances - i) + ' chances left')
# You can do whatever you want in a block ...
else:
print('No, the number is lower than that, keep guessing, you have ' + str(num_chances - i) + ' chances left')
# you must have guessed > number to reach here
print('Done')
- 4.2_控制流2while__range语句.docx
- 4.3_控制流3break_continue__pass.docx
- 4.1_控制流1_if__for_语句
- JAVA _控制语句
- 04_条件控制语句
- Python基本语法_控制流语句_if/while/for
- JHTP小结_第五章_控制语句Part 2-逻辑运算符
- JHTP自测题_第五章_控制语句Part 2-逻辑运算符
- JHTP练习题及课题_第五章_控制语句Part 2-逻辑运算符
- Java基础_流程控制语句
- 程序流程控制_循环语句_break_continue
- 黑马程序员_程序流程控制语句
- 黑马程序员_流程控制语句
- 黑马程序员_流程控制语句
- 黑马程序员_流程控制语句
- C语言 关键字_控制语句_运算符
- 运算符_键盘录入_流程控制语句
- 黑马程序员_流程控制语句之循环语句
- resource fork, Finder information, or similar detritus not al site:forums.developer.apple.com..
- 项目管理和构建】十分钟教程,eclipse配置maven + 创建maven项目
- 【bzoj 2456】mode(乱搞)
- 240. Search a 2D Matrix II
- Oracle sql性能优化1
- 4.2_控制流2while__range语句.docx
- [Git] Git初应用
- 使用visual studio 2017 创建动态链接库(DLL),供VB6.0使用
- 自由幻想UI之信息显示
- utunbu安装中文输入法(转载)
- [Oracle]理解undo表空间
- 4.3_控制流3break_continue__pass.docx
- 设计模式深入浅出(一)对象创建——工厂方法,抽象工厂
- Minimum Path Sum