首页 > 代码库 > Python语言之控制流(if...elif...else,while,for,break,continue)
Python语言之控制流(if...elif...else,while,for,break,continue)
1.if...elif...else...
1 number = 23 2 guess = int(raw_input(‘Enter an integer : ‘)) 3 4 if guess == number: 5 print( ‘Congratulations, you guessed it.‘ ) # New block starts here 6 print( "(but you do not win any prizes!)" ) # New block ends here 7 elif guess < number: 8 print( ‘No, it is a little higher than that‘ )# Another block 9 else:10 print( ‘No, it is a little lower than that‘ )11 12 print( ‘Done‘ )13 # This last statement is always executed, after the if statement is executed
2.while
1 number = 23 2 running = True 3 4 while running: 5 guess = int(raw_input(‘Enter an integer : ‘)) 6 7 if guess == number: 8 print ‘Congratulations, you guessed it.‘ 9 running = False # this causes the while loop to stop10 elif guess < number:11 print ‘No, it is a little higher than that‘12 else:13 print ‘No, it is a little lower than that‘14 else:15 print ‘The while loop is over.‘16 # Do anything else you want to do here17 18 print ‘Done‘
while循环条件变为False时,else块被执行。
你可能想问,这样的else块始终会被执行到,还要else干嘛。别着急,在4.break中有解答。
3.for
1 for i in range(1, 5):2 print i3 else:4 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语言之控制流(if...elif...else,while,for,break,continue)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。