码迷,mamicode.com
首页 > 编程语言 > 详细

Python语言之控制流(if...elif...else,while,for,break,continue)

时间:2014-10-28 15:22:41      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   ar   for   sp   strong   

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 stop
10     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 here
17 
18 print Done

while循环条件变为False时,else块被执行。

你可能想问,这样的else块始终会被执行到,还要else干嘛。别着急,在4.break中有解答。

3.for

1 for i in range(1, 5):
2     print i
3 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)

标签:style   blog   io   color   os   ar   for   sp   strong   

原文地址:http://www.cnblogs.com/magnolia/p/4056471.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!