python入門基礎教程10 python的分支語句

if分支語句

分支語句的作用是在某些條件控制下有選擇的執行實現一定功能語句塊。if 分支語句則是當if後的條件滿足時,if 下的語句塊被執行,語法格式如下所示:

if <condition>:
    statements

讓我們看看代碼吧。

>>> sex = 'male'
>>> if sex == 'male': 
    print 'Man!'#此處有兩次回車鍵
Man!
>>> if sex == 'female':
       print 'Woman'#此處有兩次回車鍵
>>>

if_else語句

if語句下的語句塊是在<condition>條件滿足時執行,else 語句下的語句塊則是在<condition>條件不滿足的情況下執行,使用if_else 語句需要注意的是if的<condition>判定條件後有冒號,else 語句後無<condition>判定表達式,但有冒號。if 和else下的語句塊不用左右花括號。

if <condition>:
    statementselse:
    statements

舉個例子來說明一下if_else的使用。

sex = raw_input("plz input your sex: ")
if sex == 'male' or sex == 'm':       
   print 'Man!'
else: 
   print 'Woman!'

程序運行結果如下:

plz input your sex: female
Woman

做個小練習,輸入數學成績(整形),060打印“No Pass!”,6070打印“Just Pass!”,
7080 打印“Good”,7080打印“Wonderful!”,8090打印“Excellent!”,90100打印“Best!”,請用if_else嵌套來完成。

#coding:utf-8

x = input("plz input math record: ")
if x >= 60:    
    if x >= 70:        
       if x >= 80:            
          if x >= 90:  
              print "Best!"
          else:
              print "Excellent!"
       else:
          print "Good!"
    else: 
       print "Just Pass!"
else:
    print "No Pass!"

程序運行結果如下

>>> ========= RESTART =========
plz input math record: 27No Pass!
>>> ========= RESTART =========
plz input math record: 67Just Pass!
>>> ========= RESTART =========
plz input math record: 77Good!
>>> ========= RESTART =========
plz input math record: 80Excellent!
>>> ========= RESTART =========
plz input math record: 98Best!
>>>

if_elif_else多分支語句

上邊的程序如果寫不好,很有可能無法完成對成績的分類打印,諸如用if_else 嵌套完成的程序可以用if_elif_elif_.....elif_else結構來完成,其語法結構如下所示:

if <condition1>:
    statements_1
elif <condition2>:
    statements_2
elif <condition3>:
    statements_3
...
...
...
elif <conditionN>:
    statements_n
else:
    statements_else

這種結構稱之爲多分支結構,從上if 至下elif 逐一檢查判定條件表達式上
<conditionX>,看那個條件滿足就執行其下的語句塊上 statements_X,所有條件均不滿足才執行else 下的語句塊statements_else。 整個結構只有一個語句塊被執行。由此上一小節的分類打印成績的程序可以改成下面這個樣子了。

if x >= 90:
    print "Best!"
elif x >= 80:
    print "Excellent!"
elif x >= 70:
    print "Good!"
elif x >= 60:
    print "Just Pass!"
else:
    print "No Pass!"

小練習:寫一個完備的判斷性別的程序。(鍵入 ’male’,’Male’,’m’,’M’,’man’,’Man’ 均代表男性)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章