「如果 ... 就 ... 否則 ... 」
conditional statement (判斷式)
「如果室內溫度超過 28 度時,就啟動冷氣運作。」
「如果感測器所偵測的數值大於 60 時,
就點亮紅色警示燈,否則點亮綠色警示燈。」
if condition:
do condition True things
.
.
.
Indentation 縮排
score = int(input("請輸入分數"))
if score >= 60: #如果分數大於等於60 則成績及格:)
print("成績及格 :)")
score = int(input("請輸入分數"))
if score >= 60: #如果分數大於等於60 則成績及格:)
print("成績及格 :)")
請輸入分數 100
成績及格 :)
if condirtion:
do condition True things
.
.
.
else:
do condition False things
.
.
.
score = int(input("請輸入分數"))
if score >= 60: #如果分數大於等於60 則成績及格:)
print("成績及格:)")
else: #否則分數小於60 成績不及格!!
print("成績不及格!!")
請輸入分數 100
成績及格:)
請輸入分數 50
成績不及格!!
score = int(input("請輸入分數"))
if score >= 60: #如果分數大於等於60 則成績及格:)
print("成績及格:)")
if score < 60: #如果分數小於60 則成績不及格!!
print("成績不及格!!")
請輸入分數 100
成績及格:)
請輸入分數 50
成績不及格!!
if condirtion_1:
do condition_1 True things
...
elif condition_2:
do condition_2 False things
...
.
.
.
elif condition_n:
do condition_n False things
...
else:
do all conditions False things
...
and : 且
score = int(input("score: "))
if 90 <= score and score <= 100:
print('Grade is: A')
elif 80 <= score and score < 90:
print('Grade is: B')
elif 70 <= score and score < 80:
print('Grade is: C')
elif 60 <= score and score < 70:
print('Grade is: D')
else:
print('Grade is: F')
score: 100
Grade is: A
score = int(input("score: "))
if 90 <= score <= 100:
print('Grade is: A')
elif 80 <= score < 90:
print('Grade is: B')
elif 70 <= score < 80:
print('Grade is: C')
elif 60 <= score < 70:
print('Grade is: D')
else:
print('Grade is: F')
score: 100
Grade is: A
score = int(input("score: "))
if score >= 90:
print('Grade is: A')
elif score >= 80:
print('Grade is: B')
elif score >= 70:
print('Grade is: C')
elif score >= 60:
print('Grade is: D')
else:
print('Grade is: F')
score: 60
Grade is: D
answer = input("Do you agree? ")
if answer == 'yes':
print("Agreed")
else:
print("Not Agreed")
answer = input("Do you agree? ").strip().lower()
if answer == 'yes':
print("Agreed")
else:
print("Not Agreed")
answer = input("Do you agree? ").strip().lower()
if answer == 'yes' or answer == 'y'
print("Agreed")
else:
print("Not Agreed")
day = input("今天星期幾呢?")
if day == "Monday":
print("新的星期,加油!")
elif day == "Tuesday":
print("這禮拜你將完成很多事情!")
elif day == "Wednesday":
print("第三天,好好發揮工作精神!")
elif day == "Thursday":
print("你已經撐過一半了!")
elif day == "Friday":
print("再撐一天就好了!")
elif day == "Saturday":
print("假期愉快 ^.^")
elif day == "Sunday":
print("把握假期的最後一天!")
else:
print("你是不是輸入錯誤了呢?")
今天星期幾呢? Friday
再撐一天就好了!
今天星期幾呢? 1
你是不是輸入錯誤了呢?
name = input("What's your name? ")
match name:
case "Harry":
print("Gryffindor")
case "Hermione":
print("Gryffindor")
case "Ron":
print("Gryffindor")
case "Draco":
print("Slytherin")
case _:
print("Who?")
What's your name? Harry
Gryffindor
讓使用者輸入一個數字,判斷它是不是7的倍數
Hint : 數字除以7,如果能整除,就是7的倍數 x % 7 == 0, x 就是7的倍數
% 求餘數 ==> X % Y 求 X 除以 Y 的餘數