流程控制是程序设计中一个重要的内容,Python支持三种不同的控制结构:if,for和while。
-
if语句判断表达式是否为真,如果为真则执行指定语句。if语句的格式如下:
if EXPRESSION1: STATEMENT1 elif EXPRESSION2: STATEMENT2 else: STATEMENT3
如果第一个表达式为真,则执行statement1,否则进行进一步的测试,如果第二个表达式为真则执行statement2,否则执行statement3。
注意语句的缩进量要保持一致。在python中没有switch和case语句,我们可通过多重elif来达到相同的效果。 示例:
#!/usr/bin/env python mytest = raw_input("please input a number:") mytest = int(mytest) if mytest == 10: print "you input number is ten." elif mytest == 20: print "you input number is twenty." else: print "another number." 脚本的执行效果: t03:~# python test.py please input a number:10 you input number is ten. t03:~# python test.py please input a number:20 you input number is twenty. t03:~# python test.py please input a number:777 another number.
-
while进行循环控制,它对表达式进行测试,如果为真,则循环执行循环体。格式如下:
while EXPRESSION: STATEMENT else: STATEMENT
如果测试为假,则会执行else块。如果循环被中断(break),则else块不会执行。
示例:
>>> a = 0 >>> while a < 5: ... a = a + 1 ... print a ... else: ... print "a's value is five" ... 1 2 3 4 5 a's value is five
-
for循环可遍历对象,并可进行迭代操作。语名格式如下:
for TARGET in OBJECTS: STATEMENT else: STATEMENT
和while一样,在循环正常退出时,会执行else块。
示例:
>>> mylist = "for statement" >>> for word in mylist: ... print word ... else: ... print "End list" ... f o r s t a t e m e n t End list
-
在循环的过程中,我们可使用循环控制语句来控制循环的执行。有三个控制语句,分别是break、continue和pass。它们的作用分别是:
-
break语句会立即退出当前循环,不会执行else块的内容。
示例:
>>> mylist = ["zope","python","perl","Linux"] >>> for technic in mylist: ... if technic == "perl": ... break ... else: ... print technic ... zope python
-
continue语句会忽略后面的语句,强制进入下一次循环。
示例:
>>> mylist = ["zope","python","perl","Linux"] >>> for technic in mylist: ... if technic == "perl": ... continue ... else: ... print technic ... zope python Linux
-
pass不做任何事情。
示例:
>>> for technic in mylist: ... if technic == "perl": ... pass ... else: ... print technic ... zope python Linux
-