9.條件陳述句
9.1 基本語法
? ? 在編程語言中,會經常碰到在不同條件下完成不同的操作功能,在Python中僅提供了if-elfif...else等條件陳述句,并未提供其他語言中的switch陳述句(如果深刻字典,也可以用字典實作switch功能),其基本語法格式如下所示:
1.基本格式
if condition:
doSomething
elif condition:
doSomething
...
else:
doSomething
2.嵌套格式
if condition:
if condition:
doSomething
else:
doSomething
elif condition:
if condition:
doSomething
elif condition:
doSomething
else:
doSomething
...
else
if condition:
doSomething
else:
doSomething
? ? 基本變異形式示意圖如下所示:



9.2 三元運算子
? ? 相信有其他編程語言基礎的童鞋都知道三元運算子,Python同樣也提供了,基本格式如下所示:
[result = ] TrueResult if condition else FalseResult
? ? 心細的童鞋,應該發現前面的示例中已經用到這種格式的三元運算子了,可以在實踐中多使用體會,
9.3 字典實作switch條件判斷
? ? 可能有其他編程語言基礎的童鞋比較懷念switch陳述句,而Python官方卻又沒有提供這個條件判斷方法,我們一直來看看,如何結合字典來實作switch功能吧,示例代碼如下所示:
def add(x:int,y:int)->int:
print( x+y)
def sub(x:int,y:int)->int:
print( x-y)
def mul(x:int,y:int)->int:
print( x*y)
def div(x:int,y:int)->int:
if y:
print( x/y)
def simpleCaculator(operator:str,x:int,y:int)->None:
dic={
"+":add,
"-":sub,
"*":mul,
"/":div,
}
return dic.get(operator)(x,y)
if __name__ == '__main__':
simpleCaculator("+", 1, 2)
simpleCaculator("-", 1, 2)
simpleCaculator("*", 1, 2)
simpleCaculator("/", 1, 2)
? ? 以上其實運用函式在Python是一等公民的特性(后面會講),運行結果如下所示:
3
-1
2
0.5
9.4 示例代碼
? ? 示例代碼如下所示:
tmpStr=int(input("請輸入一個數字:"))
if tmpStr<0:
print("您輸入的數字小于0")
elif tmpStr<100:
if 0<=tmpStr<=50:
print("您輸入的數字介于[0,50]")
elif 50<tmpStr<=100:
print("您輸入的數字介于(50,100]")
else:
if 100<tmpStr<=999:
print("您輸入的數字介于(100,999]")
else:
print("您輸入的數字太大了,暫時不輸出資訊")
本文地址:https://www.cnblogs.com/surpassme/p/12969222.html
本文同步在微信訂閱號上發布,如各位小伙伴們喜歡我的文章,也可以關注我的微信訂閱號:woaitest,或掃描下面的二維碼添加關注:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/142355.html
標籤:Python
上一篇:Python基礎-08資料嵌套
