[英]The code won't recognize my if statement (Python)
該代碼將無法識別我的if語句。 當我運行此代碼時,我輸入以下數字:-10。 但是,當應返回if語句時,它將返回else語句。 任何我做錯的幫助嗎?
def distance_from_zero(d):
if type(d)== int or type(d)==float:
return abs(d)
else:
return "Not an integer or float!"
x = raw_input("Enter number: ")
print distance_from_zero(d)
raw_input
始終返回一個字符串。 因此,如果鍵入數字9,則不返回整數9
,而是返回字符串"9"
。 因此,您的測試type(d)== int or type(d)==float
永遠是不正確的。
你可以做類似的事情
def distance_from_zero(d):
try:
return abs(int(d))
except ValueError:
pass
try:
return abs(float(d))
except ValueError:
pass
return "Not an integer or float!"
x = raw_input("Enter number: ")
print distance_from_zero(x)
這利用了一種在python中流行的稱為“鴨子類型”的設計原理,在這種設計中,您無需測試對象的類型,而只是將對象視為所需的任何類型,並處理彈出的異常如果不是那種類型的話。
原始輸入返回字符串,而不是int或float。 嘗試對您從raw_input()獲得的變量進行類型轉換,以將其設置為int或float。
x
始終是來自raw_input
的string
。
有關內置模塊中內置函數raw_input的幫助:
raw_input(...)raw_input([提示])->字符串
Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading. (END)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.