判斷式IF
1.條件成立時,做事。
2.條件成立時,做事、不成立時,做事。
小實作:
單個條件成立時,執行
1.條件成立時,做事。
如果 (條件回傳True) : 當條件成立時執行
light = -1 #-1關 ,1 開
if (light > 0) : print("open")
條件式的地方不加括弧( )也可以執行
light = 1 #-1關 ,1 開
if light > 0 : print("open")
如果要將成立時執行的程式碼分成兩行也可以,但是要記得縮排
light = 1 #-1關 ,1 開
if (light > 0) :
print("open")
2.條件成立時,做事、不成立時,做事。
light = -1
if (light > 0):
print("open")
else:
print("close")
小實作1:
請設計一個程式(判斷使用者想要開燈或關燈)
印出 使用者想要開燈或關燈
print("請輸入 1.關燈 2.開燈")
light = input()
if (light == "2"):
print("open")
else:
print("close")

小實作2:
請設計一個程式
請使用者輸入姓名、性別
判斷使用者性別後
印出 "姓名,先生您好"
或者
印出 "姓名,小姐您好"
name = input("請輸入姓名: ")
gender = input("請輸入性別 : 1.男 、2.女 ")
if (gender == "1"):
print(name,"先生您好")
else:
print(name,"小姐您好")

實作3:
設計一個程式,讓使用者輸入姓名與身分證字號,程式將根據身分證字號的第 2 位數來判斷性別並輸出適當的問候語。
需求:
- 使用者需輸入「姓名」與「身分證字號」。
- 身分證字號的第 2 位數為
1
表示男性,為2
表示女性。 - 根據性別輸出對應的問候語:
- 男性:
{姓名}, 先生您好
- 女性:
{姓名}, 小姐您好
- 男性:
name=input("請輸入姓名:")
id_num=input("請輸入身分證:")
gender=id_num[1]
if(gender=="1"):
print(name+"先生您好")
else:
print(name+"小姐您好")

Yiru@Studio - 關於我 - 意如