Python if 語(yǔ)句

Document 對(duì)象參考手冊(cè) Python3 實(shí)例

以下實(shí)例通過(guò)使用 if...elif...else 語(yǔ)句判斷數(shù)字是正數(shù)、負(fù)數(shù)或零:

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.o2fo.com

# 用戶輸入數(shù)字

num = float(input("輸入一個(gè)數(shù)字: "))
if num > 0:
   print("正數(shù)")
elif num == 0:
   print("零")
else:
   print("負(fù)數(shù)")

執(zhí)行以上代碼輸出結(jié)果為:

$ python test.py 
輸入一個(gè)數(shù)字: 3
正數(shù)

我們也可以使用內(nèi)嵌 if 語(yǔ)句來(lái)實(shí)現(xiàn):

# -*- coding: UTF-8 -*-

# Filename :test.py
# author by : www.o2fo.com

# 內(nèi)嵌 if 語(yǔ)句

num = float(input("輸入一個(gè)數(shù)字: "))
if num >= 0:
   if num == 0:
       print("零")
   else:
       print("正數(shù)")
else:
   print("負(fù)數(shù)")

執(zhí)行以上代碼輸出結(jié)果為:

$ python test.py 
輸入一個(gè)數(shù)字: 0
零

Document 對(duì)象參考手冊(cè) Python3 實(shí)例