Python语言之控制流(if...elif...else,while,for,break,continue)
2024-08-30 23:04:58
1.if...elif...else...
number = 23
guess = int(input('Enter an integer : ')) if guess == number:
print( 'Congratulations, you guessed it.' ) # New block starts here
print( "(but you do not win any prizes!)" ) # New block ends here
elif guess < number:
print( 'No, it is a little higher than that' )# Another block
else:
print( 'No, it is a little lower than that' ) print( 'Done' )
# This last statement is always executed, after the if statement is executed
2.while
number = 23
running = True while running:
guess = int(input('Enter an integer : ')) if guess == number:
print( 'Congratulations, you guessed it.' )
running = False # this causes the while loop to stop
elif guess < number:
print( 'No, it is a little higher than that' )
else:
print( 'No, it is a little lower than that' )
else:
print( 'The while loop is over.' )
# Do anything else you want to do here print( 'Done' )
while循环条件变为False时,else块被执行。
你可能想问,这样的else块始终会被执行到,还要else干嘛。别着急,在4.break中有解答。
3.for
for i in range(1, 5):
print( i )
else:
print ( 'The for loop is over' )
range(n, m [,stepLen]) = [n,n+stepLen,n+stepLen*2,...,n+(ceil((m-n)/stepLen)-1)*stepLen]
即从n开始,以stepLen为步长,一直到小于m的序列(不包括m)。默认情况下stepLen=1。
4.break
终止当前循环语句。
注意如果从for或while循环终止,任何对应的else将不会被执行。
5.continue
跳过当前循环块中的剩余语句,然后继续进行下一轮的循环。
最新文章
- 关于python数据序列化的那些坑
- Cycles渲染研究测试效果图
- spring加载bean实例化顺序
- [转]❲阮一峰❳Linux 守护进程的启动方法
- Ajax分页js代码
- Web API 2 authentication with JWT
- https://docs.mongodb.org/manual/reference/operator/aggregation/unwind/#examples
- 用jquery ,当改变窗口或屏幕大小时调用function,用哪个事件?
- UAT测试,PPT测试
- 启动Tomcat出现Using CATALINA_BASE
- Linux下Nagios
- String.Format(string, arg0)中sring格式
- ural1890 Money out of Thin Air
- ServerSuperIO Designer IDE 发布,打造物联网通讯大脑,随心而联。附:C#驱动源代码。
- SQLServer 数据库重命名
- vb.net 使用NPO各種格式設定
- MYSQL之 error while loading shared libraries: libtinfo.so.5: cannot open shared objectfile: No such f
- hdu1255扫描线计算覆盖两次面积
- CocosCreator项目结构
- FireMonkey 源码学习(1)