if 語句(如果)elif(或者如果)else(否則)
問題:
有兩條語句
print("是偶數") print("是奇數")
如何只讓其中的一條語句執行,另一個不執行?
語法:
if 真值表達式1: 語句塊1 elif 真值表達式2: 語句塊2 elif 真值表達式3: 語句塊3 ...#此處可以有多個elif 子句 else: 語句塊4
作用:
讓程序根據條件選擇性的執行某條語句或某些語句
說明:
elif 子句可以有0個,1個或多個
else 子句可以有0個或1個,且只能放在最后
子句里的語句要縮進4個空格
#示例: x = int(input("請輸入一個整數:")) if x % 2 ==1: print(x,"是奇數") else: print(x,"是偶數")
練習:
1.輸入一個數,然后做下面兩步判斷:
1)判斷這個數是否在50~100之間1
2)判斷這個數是否小於0
x = int(input("請輸入一個數:")) if 50<=x<=100: print(x,"在50~之間")
else: print(x,"不在50~100之間") if x<0: print(x,"小於0") else: print(x,"大於0")
#示例:三選一 # 輸入一個整數,讓程序來打印出這個數是正數,零,負數 x = int(input("請輸入一個數字:")) if x > 0: print(x,"是正數") elif x < 0: print(x,"是負數") else: print(x,"是零")
cookie(軟件使用)
visual studio code 軟件使用
打開終端: 查看----->終端 快捷鍵: ctrl + / 注釋和取消注釋 ctrl + s 保存(重要) shift + tab 向右縮進 ctrl + shift + tab 向左縮進 ctrl + d 選中相同的內容,產生多個光標 ctrl + b 關閉/打開左側側邊欄 調試: 調試----> 啟動調試(快捷鍵:F5)
練習:
1.輸入一個季度 1~4 輸出這個季度有哪兒幾個月
如果輸入的不是1~4的數,則提示用戶“你輸錯了”
y = int(input("請輸入一個月份:")) if 3<=y<=5: print("春季") elif 6<=y<=8: print("夏季") elif 9<=y<=11: print("秋季") elif 1<=y<=12: print("冬季") else: print("你輸錯了")
if 語句的真值表達式:
if 100: print("真值") # 等同於 if bool(100): print("真值")
if 語句
if 真值表達式1 語句塊(注:語句塊內的語句要有相同的縮進) elif 真值表達式2: .... else: 語句塊3
if 語句的嵌套:
if 語句體身是有多條子句組成的一條復合語句
if 語句可以作為語句嵌套到另一個復合語句的內部
# 示例: # 輸入一個整數1~12代表月份,打印這個月在那個季度 month = int(input("請輸入月份(1~12):")) if 1 <= month <=12: print("合法的月份") if month <= 3: print("春季") elif month <= 6: print("夏季") elif month <=9: print("秋季") else: print("冬季") else: print("你輸入有錯")
條件表達式
語法:
表達式1 if 真值表達式 else 表達式2
作用:
根據真值表達式的取值(True/False)來決定執行表達式1或表達式2並返回結果
# 示例: m = int(input("請輸入商品總金額:")) pay = m - 20 if m >= 100 else m print("你需要支付:",pay,"元")
練習:
1.寫一個程序,輸入一個數,用if語句計算這個數的絕對值,並打印此絕對值
x = int(input("請輸入一個數字:")) result = -x if x < 0 else x print(x,"絕對值是",result)
pass 語句
作用:
通常用來填充語句空白
語法:
pass
# 讓程序輸入一個學生的成績(0~100之間),如果不在這個范圍內則報錯 score = int(input("請輸入學生成績:")) if 0<=score<=100: # print("成績合法") pass else: print("成績不合法,輸入有錯!")
布爾運算
運算符:
not(不) and(與) or(或)
布爾非操作 not
語法:
not x
作用:
對 x 進行 布爾取非,如bool(x) 為True,則返回False,否則
返回True
# 示例: not True # False not False # True not 1 > 2 # True not 100 # False
布爾與操作 and
語法:
x and y
注:x,y代表表達式
作用:
優先返回假值對象
當x的布爾值為False時,返回x,否則返回y
# 示例: True and True # True True and False # False False and True # False False and False # False 30 and 50 # 50 0.0 and 0 # 0.0 優先返回假值對象
布爾或操作 or
語法:
x or y
作用:
優先返回真值對象
當x為True時,返回x,否則返回y
# 示例: True or True # True True or False # True False or True # True False or False # False 30 or 50 # 30 0.0 or 0 # 0
正負號運算符:
+(正號) -(負號)
說明:
一元運算符
語法:
+ 表達式
- 表達式
# 示例: a = 5 b = -a # b=-5 c = +a # c=5