1. 程式人生 > 程式設計 >python中if及if-else如何使用

python中if及if-else如何使用

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:
  # 比較運算子(== 相等 、!= 不等、> 大於、>= 大於等於、< 小於、<=小於等於)
  if dessert == favorite_dessert:
    print("%s is my favorite dessert!" % dessert.title())
  # elif => else + if 當前值不符合上面 if 的判斷條件,執行 elif 的判斷條件
  else:
    print("I like %s." % dessert)

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

# 對不同的 dessert 輸出不完全相同的結果
for dessert in desserts:
  # 比較運算子(== 相等 、!= 不等、> 大於、>= 大於等於、< 小於、<=小於等於)
  if dessert == favorite_dessert:
    print("%s is my favorite dessert!" % dessert.title())
  # elif => 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中條件語句總結內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!