(一)Python入門-4控制語句:04多分支選擇結構-選擇結構的嵌套


一:多分支選擇結構

  多分支選擇結構的語法格式如下:

    if 條件表達式 1 :

      語句 1/語句塊 1

    elif 條件表達式 2:

      語句 2/語句塊 2

    .

    .

    elif 條件表達式 n :

      語句 n/語句塊n

    [else:

      語句 n+1/語句塊 n+1

    ]

  注:多分支結構,幾個分支之間是有邏輯關系的,不能隨意顛倒順序。

【操作】輸入一個學生的成績,將其轉化成簡單描述:不及格(小於60)、及格(60-79)、良 好(80-89)、優秀(90-100)。

 1 #多分支選擇測試
 2 #方法一:使用完整的條件表達:每個分支都使用了獨立的、完整的判斷,順序可以隨意挪動,而不影響程序運行
 3 score = int(input('請輸入分數:'))
 4 grade = ''
 5 if score<60:
 6     grade = '不及格'
 7 if 60<=score<80:
 8     grade = '及格'
 9 if 80<=score<90:
10     grade = '良好'
11 else:
12     grade = '優秀'
13 print('分數是{0},等級是{1}'.format(score,grade))
14 
15 #方法二:利用多分支結構:幾個分支之間是有邏輯關系的,不能隨意顛倒順序
16 score1 = int(input('請輸入分數:'))
17 grade1 = ''
18 if score<60:
19     grade1 = '不及格'
20 elif score<80:
21     grade1 = '及格'
22 elif score<90:
23     grade1 = '良好'
24 else:
25     grade1 = '優秀'
26 
27 print('分數是{0},等級是{1}'.format(score1,grade1))

【操作】已知點的坐標(x,y),判斷其所在的象限

 1 x = int(input('請輸入x坐標:'))
 2 y = int(input('請輸入y坐標:'))
 3 if x==0 and y==0:print('原點')
 4 elif x==0:print('y軸')
 5 elif y==0:print('x軸')
 6 elif x>0 and y>0:print('第一象限')
 7 elif x<0 and y>0:print('第二象限')
 8 elif x<0 and y<0:print('第三象限')
 9 else:
10     print('第四象限')

二:選擇結構嵌套

  選擇結構可以嵌套,使用時一定要注意控制好不同級別代碼塊的縮進量,因為縮進量決定了 代碼的從屬關系。語法格式如下:

    if 表達式 1:

      語句塊1

      if 表達式 2:

        語句塊2

      else:

        語句塊3

    else:

      if 表達式 4:

        語句塊4

【操作】輸入一個分數。分數在 0-100 之間。90 以上是A,80 以上是 B,70以上是 C,60 以上是D。60 以下是E。

 1 #方式一:
 2 score2 = int(input('請輸入一個0-100之間的數字:'))
 3 grade2 = ''
 4 if score2>100 or score2<0:
 5     score2 = int(input('輸入錯誤,請重新輸入一個0-100之間的數字:'))
 6 else:
 7     if score2>=90:
 8         grade2 = 'A'
 9     elif score2>=80:
10         grade2 = 'B'
11     elif score2>=70:
12         grade2 = 'C'
13     elif score2>=60:
14         grade2 = 'D'
15     else:
16         grade2 = 'E'
17 print('分數是{0},等級是{1}'.format(score2,grade2))
18 #方式二:
19 score3 = int(input('請輸入一個0-100之間的數字:'))
20 degree = 'ABCDE'
21 num = 0
22 if score3>100 or score3<0:
23     score3 = int(input('輸入錯誤,請重新輸入一個0-100之間的數字:'))
24 else:
25     num = score3//10
26     if num<6:num=5
27     if num>=10:num=9
28 print('分數是{0},等級是{1}'.format(score3,degree[9-num]))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM