python中if及if-else如何使用
if 結(jié)構(gòu)
if 結(jié)構(gòu)允許程序做出選擇,并根據(jù)不同的情況執(zhí)行不同的操作
基本用法
比較運(yùn)算符
根據(jù) PEP 8 標(biāo)準(zhǔn),比較運(yùn)算符兩側(cè)應(yīng)該各有一個(gè)空格,比如:5 == 3。 PEP8 標(biāo)準(zhǔn)
==(相等):如果該運(yùn)算符兩側(cè)的值完全相同則返回 True
!=(不等):與相等相反
print(5 == ’5’)print(True == ’1’)print(True == 1)print(’Eric’.lower() == ’eric’.lower())
>(大于):左側(cè)大于右側(cè)則輸出 True
<(小于):與大于相反
>=(大于等于):左側(cè)大于或者等于右側(cè)則輸出 True
<=(小于等于):左側(cè)小于或者等于右側(cè)則輸出 True
print(5 > 3)print(2 > True)print(True > False)
if的用法
1.只有 if 進(jìn)行判斷
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 進(jìn)行判斷
for dessert in desserts: # 比較運(yùn)算符(== 相等 、!= 不等、> 大于、>= 大于等于、< 小于、<=小于等于) if dessert == favorite_dessert: print('%s is my favorite dessert!' % dessert.title()) # elif => else + if 當(dāng)前值不符合上面 if 的判斷條件,執(zhí)行 elif 的判斷條件 else: print('I like %s.' % dessert)
3. if - elif - else 進(jìn)行判斷,其中 elif 不是唯一的,可以根據(jù)需要添加,實(shí)現(xiàn)更細(xì)粒度的判斷
# 對(duì)不同的 dessert 輸出不完全相同的結(jié)果for dessert in desserts: # 比較運(yùn)算符(== 相等 、!= 不等、> 大于、>= 大于等于、< 小于、<=小于等于) if dessert == favorite_dessert: print('%s is my favorite dessert!' % dessert.title()) # elif => else + if 當(dāng)前值不符合上面 if 的判斷條件,執(zhí)行 elif 的判斷條件 elif dessert == hate_dessert: print('I hate %s.' % dessert) # 當(dāng)前值不符合上面所有的判斷條件,就執(zhí)行 else 里的語(yǔ)句 # 當(dāng)然如果這個(gè)else 不需要的話,可以不寫 else: print('I like %s.' % dessert)
值得注意的一點(diǎn)是:當(dāng)整個(gè) if 判斷滿足某一個(gè)判斷條件時(shí),就不會(huì)再繼續(xù)判斷該判斷條件之后的判斷
4.特殊的判斷條件
if 0: # 其他數(shù)字都返回 True print('True.')else: print('False.') # 結(jié)果是這個(gè)if ’’: #其他的字符串,包括空格都返回 True print('True.')else: print('False.') # 結(jié)果是這個(gè)if None: # None 是 Python 中特殊的對(duì)象 print('True.')else: print('False.') # 結(jié)果是這個(gè) if 1: print('True.') # 結(jié)果是這個(gè)else: print('False.')
實(shí)例擴(kuò)展:
實(shí)例(Python 3.0+)實(shí)例一:
# Filename : test.py# author by : www.runoob.com # 用戶輸入數(shù)字 num = float(input('輸入一個(gè)數(shù)字: '))if num > 0: print('正數(shù)')elif num == 0: print('零')else: print('負(fù)數(shù)')
實(shí)例(Python 3.0+)實(shí)例二:
# Filename :test.py# author by : www.runoob.com # 內(nèi)嵌 if 語(yǔ)句 num = float(input('輸入一個(gè)數(shù)字: '))if num >= 0: if num == 0: print('零') else: print('正數(shù)')else: print('負(fù)數(shù)')
到此這篇關(guān)于python中if及if-else如何使用的文章就介紹到這了,更多相關(guān)python中條件語(yǔ)句總結(jié)內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 解決Python 進(jìn)程池Pool中一些坑2. 三個(gè)不常見(jiàn)的 HTML5 實(shí)用新特性簡(jiǎn)介3. Python獲取抖音關(guān)注列表封號(hào)賬號(hào)的實(shí)現(xiàn)代碼4. Python使用jupyter notebook查看ipynb文件過(guò)程解析5. ajax請(qǐng)求添加自定義header參數(shù)代碼6. python利用os模塊編寫文件復(fù)制功能——copy()函數(shù)用法7. Python如何讀寫CSV文件8. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究9. php測(cè)試程序運(yùn)行速度和頁(yè)面執(zhí)行速度的代碼10. 無(wú)線標(biāo)記語(yǔ)言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁(yè)
