歡迎您光臨本站 註冊首頁

python中if及if-else如何使用

←手機掃碼閱讀     f2h0b53ohn @ 2020-06-04 , reply:0

if 結構

if 結構允許程序做出選擇,並根據不同的情況執行不同的操作

基本用法

比較運算符

根據 PEP 8 標準,比較運算符兩側應該各有一個空格,比如:5 == 3。 PEP8 標準

==(相等):如果該運算符兩側的值完全相同則返回 True

!=(不等):與相等相反

 print(5 == '5') print(True == '1') print(True == 1) print('Eric'.lower() == 'eric'.lower())


>(大於):左側大於右側則輸出 True

<(小於):與大於相反

>=(大於等於):左側大於或者等於右側則輸出 True

<=(小於等於):左側小於或者等於右側則輸出 True

 print(5 > 3) print(2 > True) print(True > False)


if的用法

1.只有 if 進行判斷

 desserts = ['ice cream', 'chocolate', 'apple crisp', 'COOKIEs'] favorite_dessert = 'apple crisp' hate_dessert = 'chocolate' for dessert in desserts: if dessert == favorite_dessert: print("%s is my favorite dessert!" % dessert.title())


2. if - else 進行判斷

 for dessert in desserts: # 比較運算符(== 相等 、!= 不等、> 大於、>= 大於等於、<小於、 else + if 當前值不符合上面 if 的判斷條件,執行 elif 的判斷條件 else: print("I like %s." % dessert)


3. if - elif - else 進行判斷,其中 elif 不是唯一的,可以根據需要添加,實現更細粒度的判斷

 # 對不同的 dessert 輸出不完全相同的結果 for dessert in desserts: # 比較運算符(== 相等 、!= 不等、> 大於、>= 大於等於、<小於、 else + if 當前值不符合上面 if 的判斷條件,執行 elif 的判斷條件 elif dessert == hate_dessert: print("I hate %s." % dessert) # 當前值不符合上面所有的判斷條件,就執行 else 裡的語句 # 當然如果這個else 不需要的話,可以不寫 else: print("I like %s." % dessert)


值得注意的一點是:當整個 if 判斷滿足某一個判斷條件時,就不會再繼續判斷該判斷條件之後的判斷

4.特殊的判斷條件

 if 0: # 其他數字都返回 True print("True.") else: print("False.") # 結果是這個 if '': #其他的字符串,包括空格都返回 True print("True.") else: print("False.") # 結果是這個 if None: # None 是 Python 中特殊的對象 print("True.") else: print("False.") # 結果是這個 if 1: print("True.") # 結果是這個 else: print("False.")


實例擴展:

實例(Python 3.0+)實例一:

 # Filename : test.py # author by : www.runoob.com # 用戶輸入數字 num = float(input("輸入一個數字: ")) if num > 0: print("正數") elif num == 0: print("零") else: print("負數")


實例(Python 3.0+)實例二:

 # Filename :test.py # author by : www.runoob.com # 內嵌 if 語句 num = float(input("輸入一個數字: ")) if num >= 0: if num == 0: print("零") else: print("正數") else: print("負數")


到此這篇關於python中if及if-else如何使用的文章就介紹到這了,更多相關python中條件語句總結內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支持腳本之家!


[f2h0b53ohn ] python中if及if-else如何使用已經有220次圍觀

http://coctec.com/docs/python/shhow-post-236982.html