Lesson 4: 程式的流程控制—使用if
發音: Al-go-ri-thm
演算法: 完成一件工作的一系列步驟
發音: Pro-gram
程式: 編程完成的演算法(可執行)
演算法(步驟)
向右移動一格
塗滿空格
向右移動一格
向下移動一格
塗滿空格
有5個程式指令:
上 下 左 右
填滿
程式
右
填滿
右
下
填滿
由星號出發
發音: Va-ri-able
變數: 資料內容(可改變) 的存放空間
發音: Da-ta Type
資料型別: 資料存放空間的類型
x = 5
y = input('請輸入數值')指定
半徑 = int(input('輸入:')) // 字串轉整數
面積 = 3.14 * 半徑**2; // 平方, 乘法運算
半徑字串 = input('輸入:') // 字串
半徑數值 = int(半徑字串) // 字串轉整數
面積 = 3.14 * 半徑數值**2; // 平方, 乘法
# 轉換函式: int(), float(), str(), chr()型別轉換
發音: loop
迴圈: 重複做的動作
發音: Con-di-shun-uls
條件判斷: 在某些情況才會執行的動作
if score<60:
print('不及格')
elif score<=80:
print('甲等')
else:
print('超出範圍')選擇結構
結果為真,傳回True;結果為偽,傳回False
判斷是否相等:2個等號
因為: 1個等號➞指定運算子
關係運算子
| 關係運算子 | 說明 | 實例 | 說明 |
|---|---|---|---|
| > | 大於 | a > b | 檢查是否a大於b |
| >= | 大於或等於 | a >= b | 檢查是否a大於或等於b |
| < | 小於 | a < b | 檢查是否a小於b |
| <= | 小於或等於 | a <= b | 檢查是否a小於或等於b |
| == | 等於 | a == b | 檢查是否a等於b |
| != | 不等於 | a != b | 檢查是否a不等於b |
x = 10 > 8
print(x) # 印出True
y = 10 == 10
print(y) # 印出Truex = 10 <= 5
print(x) # 印出False
y = 20 != 10
print(y) # 印出False三種邏輯運算子
❶且(and) ❷或(or) ❸非(not)
| 運算子 | 意義 | 範例 | 結果 |
|---|---|---|---|
| not | 傳回原來比較結果的相反值 | not(3>5) not(5>3) |
True False |
| and | 兩個結果都成立:True 否則:False |
(5>3) and (9>6) (5>3) and (9<6) (5<3) and (9>6) (5<3) and (9<6) |
True False False False |
| or | 兩個比較結果都不成立:False 其餘情況:True |
(5>3) and (9>6) (5>3) and (9<6) (5<3) and (9>6) (5<3) and (9<6) |
True True True False |
邏輯運算子
重複結構
循序結構
選擇結構
依序執行
二選一
多選一, 視情況而定
依序逐行執行
重複執行, 視情況而定
重複執行
book = "程式設計"
print("書名: %10s 價格: %5d" % (book, 350))
# 5d: 整數共佔5位, 不足5位前面補空白, 超過則全數印出
# 10s: 字串共佔10位, 不足前面補空白, 超過則全數印出
price = 56.6
print('價格為 %8.2f元' % price)
# 8.2f:含小數點共8位,小數點後兩位top = float(input('輸入梯形上底:'))
bottom = float(input('輸入梯形下底:'))
height = float(input('輸入梯形高度:'))
area = (top + bottom) * height / 2 # 先乘除後加減
print('面積是: %10.1f' % area)
一行一行依序執行
一行一行依序執行
前一行程式
條件判斷
程式碼區塊
程式往下執行
True
False
if
if
else
else
條件判斷
條件判斷
if(條件判斷): # 注意結尾的冒號
程式碼1 # 需縮排4格
程式碼2 # 同樣縮排距離:同一區塊
....
後續程式碼 # 不需也不能縮排 age = 18
if age < 20:
print('年齡太小')
print('需滿20歲,才能購買酒類')
print('此處為if區塊外程式碼')執行時2選1
if 敘述語法
age = 18
if age < 20:
print('年齡太小') # 錯誤,只縮3格
print('需滿20歲,才能購買酒類')
print('此處為if區塊外程式碼')注意縮排的格數
格數代表層次:0, 4, 8..., 不會有其他格數
: 加上 「縮排」代表一組「程式區塊」
if(分數>=60):
grade = "及格"
總分 += 分數程式區塊
冒號
縮排
下一行程式
英文 = int(input('輸入英文分數:'))
grade = "不及格"
if(英文>=60):
grade = "及格"
print("英文科: %d分,等第:%s" % (英文, grade))
print("英文科: %d分,等第:%s" % (英文, grade))
總分 += 英文程式區塊範例
程式區塊
# ch5_1.py
age = input("請輸入年齡: ")
if (int(age) < 20):
print("你年齡太小")
print("需年滿20歲才可以購買菸酒")請輸入年齡: 18 你年齡太小 需年滿20歲才可以購買菸酒
請輸入年齡: 21
# ch5_2.py
print("輸出絕對值")
num = input("請輸入任意整值: ")
x = int(num)
if (int(x) < 0):
x = abs(x)
print("絕對值是 %d" % int(x))輸出絕對值 請輸入任意整值: 98 絕對值是 98
輸出絕對值 請輸入任意整值: -30 絕對值是 30
英文 = int(input("輸入英文分數"))
grade = "不及格"
總分 = 0
if(英文>=60):
grade = "及格"
print("英文科: %d分,等第:%s" % (英文, grade))
print("英文科: %d分,等第:%s" % (英文, grade))
總分 += 英文
print("總分: %d" % 總分)程式區塊範例
輸入英文分數50
英文科: 50分,等第:不及格
總分: 50
執行結果1: 輸入50
執行結果2: 輸入60
輸入英文分數60
英文科: 60分,等第:及格
英文科: 60分,等第:及格
總分: 60
及格時,如何能只印一次?
...
if(字串變數=="比對內容"):
...字串比對提示
當輸入正確的通關密碼"1234"時,印出 "歡迎光臨!"
若輸入不正確, 印出 "密碼錯誤"
雙向選擇結構: 處理兩種狀況
if(條件判斷): # 注意結尾的冒號
程式區塊1 # 需縮排4格,區塊可以不止一行
else:
程式區塊2 # 需縮排4格,區塊可以不止一行
後續程式碼 # 不需縮排前一行程式
條件判斷一
程式碼區塊一
程式往下執行
True
False
程式碼區塊二
if
else
條件判斷
# ch5_3.py
age = input("請輸入年齡: ")
if (int(age) < 20):
print("你年齡太小")
print("需年滿20歲才可以購買菸酒")
else:
print("歡迎購買菸酒")請輸入年齡: 18 你年齡太小 需年滿20歲才可以購買菸酒
請輸入年齡: 21 歡迎購買菸酒
# ch5_4.py
print("奇數偶數判斷")
num = input("請輸入任意整值: ")
rem = int(num) % 2
if (rem == 0):
print("%d 是偶數" % int(num))
else:
print("%d 是奇數" % int(num))奇數偶數判斷 請輸入任意整值: 5 5 是奇數
奇數偶數判斷 請輸入任意整值: 10 10 是偶數
...
if(字串變數=="比對內容"):
...字串比對提示
當輸入正確的通關密碼"aB#12345"時,印出 "歡迎光臨!"
否則印出"密碼錯誤!"
注意: 大小寫字母不同
total = int(input("輸入總金額,超過2000元打9折:"))
if total>=2000:
print('金額 %d, 打9折後: %8.2f' % (total, total*0.9))
else:
print('金額 %d' % total)輸入總金額,超過2000元打9折:600
金額 600
輸入總金額,超過2000元打9折:2300
金額 2300, 打9折後: 2070.00
雙向選擇
...
if(score<60):
print('不及格')
if(score>=60) and (score<=80):
print('....')
if(score>80) and (score<=100):
print('....')
if(score>100):
print('超出範圍') 綜合使用提示
可視需要使用多次單向或多向
多向選擇
多向選擇
4種選擇
3種選擇
if(條件式1):
程式區塊1
elif(條件式2):
程式區塊2
else:
程式區塊3
後續程式碼多向選擇: if-elif-else語法
if(條件式1):
程式區塊1
elif(條件式2):
程式區塊2
elif(條件式3):
程式區塊3
else:
程式區塊4
後續程式碼4種選擇
3種選擇
多向選擇
score = int(input('輸入成績:'))
if score<60:
print('不及格')
elif score<=80:
print('甲等')
elif score<=100:
print('優等')
else:
print('超出範圍')...
if score<60:
print('不及格')
elif score<=80:
print('甲等')
......
if score<60:
print('不及格')
elif score>=60 and score<=80:
print('甲等')
...不需要檢驗>=60,因為第2行已檢驗過
# ch5_5.py
print("計算最終成績")
score = input("請輸入分數: ")
sc = int(score)
if (sc >= 90):
print(" A")
elif (sc >= 80):
print(" B")
elif (sc >= 70):
print(" C")
elif (sc >= 60):
print(" D")
else:
print(" F")
輸入分數,輸出分數等級:
90~100: A
80~89: B
70~79: C
60~69: D
59以下: F
# ch5_6.py
print("計算票價")
age = input("請輸入年齡: ")
age = int(age)
ticket = 100
if age >= 80 or age <= 6:
ticket = ticket * 0.2
print("票價是: %d" % ticket)
elif age >= 60 or age <= 12:
ticket = ticket * 0.5
print("票價是: %d" % ticket)
else:
print("票價是: %d" % ticket)收費標準:全票100元之外,
輸入歲數,程式計算票價
# ch5_6_1.py
print("計算票價")
age = input("請輸入年齡: ")
age = int(age)
ticket = 100
if (age >= 80) or (age <= 6):
ticket = ticket * 0.2
print("票價是: %d" % ticket)
elif (age >= 60) or (age <= 12):
ticket = ticket * 0.5
print("票價是: %d" % ticket)
else:
print("票價是: %d" % ticket)
# ch5_7.py
print("判斷輸入字元類別")
ch = input("請輸入字元: ")
if ord(ch) >= ord("A") and ord(ch) <= ord("Z"):
print("這是大寫字元")
elif ord(ch) >= ord("a") and ord(ch) <= ord("z"):
print("這是小寫字元")
elif ord(ch) >= ord("0") and ord(ch) <= ord("9"):
print("這是數字")
else:
print("這是特殊字元")
輸入字元,輸出該字元是大寫字母、小寫字母、數字、或特殊字元
ord()函式: 回傳字元的unicode編碼值
分別輸入X座標、Y座標,請判斷該座標位於第幾象限
請使用選擇敘述撰寫程式,讓使用者輸入一個西元年份,然後判斷它是否為閏年(leap year)或平年。
閏年判斷規則為:每四年一閏,每百年不閏,
但每四百年也一閏
if(條件判斷一): # 注意結尾的冒號
if(條件判斷A): # 縮排4格
程式區塊A # 需縮排8格,區塊可以不止一行
else: # 縮排4格
程式區塊B # 縮排8格
else:
程式區塊二 # 需縮排4格,區塊可以不止一行
後續程式碼 # 不需縮排巢狀if語法
注意縮排的格數,內層需全部往內多縮4格
# ch5_8.py
print("判斷輸入年份是否潤年")
year = input("請輸入年分: ")
rem4 = int(year) % 4
rem100 = int(year) % 100
rem400 = int(year) % 400
if rem4 == 0: # 被4整除
if rem100 != 0 or rem400 == 0: # 且 (不是100倍數 或 是400倍數)
print("%s 是潤年" % year)
else:
print("%s 不是潤年" % year)
else:
print("%s 不是潤年" % year)測試輸入的某一年是否為閏年
閏年判斷規則為:每四年一閏,每百年不閏,但每四百年也一閏
範例: 百貨公司折扣
money = int(input("請輸入購物金額:"))
if(money >= 10000):
if(money >= 100000):
print(money * 0.8, end=" 元\n") #八折
elif(money >= 50000):
print(money * 0.85, end=" 元\n") #八五折
elif(money >= 30000):
print(money * 0.9, end=" 元\n") #九折
else:
print(money * 0.95, end=" 元\n") #九五折
else:
print(money, end=" 元\n") #未打折範例
a = int(input('輸入數字a:'))
b = int(input('輸入數字b:'))
c = int(input('輸入數字c:'))
if a>b:
if a>c:
print('最大的數字是:a')
elif a != c:
print('最大的數字是:c')
else:
print('最大的數字是:a與c')
elif a != b:
if b>c:
print('最大的數字是:b')
elif b != c:
print('最大的數字是:c')
else:
print('最大的數字是:b與c')
else:
if a>c:
print('最大的數字是:a,b')
elif a != c:
print('最大的數字是:c')
else:
print('最大的數字是:a,b,c')x = None
print(x)
print(type(x))# ch5_9.py
flag = None
if flag == None:
print("尚未定義flag")
None
<class 'NoneType'>
可用來檢查變數是否已有值