的整數或不問我想沒有任何錯誤與IF輸入()在Python
A =input("How old are you:")
if A is int :
print ("you are",A,"years old that's awesome")
else:
print("error! type numbers only! ")
exit()
的整數或不問我想沒有任何錯誤與IF輸入()在Python
A =input("How old are you:")
if A is int :
print ("you are",A,"years old that's awesome")
else:
print("error! type numbers only! ")
exit()
input
運行這個總是產生一個字符串,所以A
始終是一個字符串
所以你在做什麼尋找的是一個try except block
A =input("How old are you:")
try:
int(A)
print("you are {} years old that's awesome".format(A))
except(ValueError):
print("error! type integers only!")
exit()
,如果他們不給你一個整數,則Int函數將引發值誤差。如果發生值錯誤,它會打印出錯信息並退出。
您的if語句不起作用,因爲變量與其類型不同。 5 is int
將返回False
而5 is 5
返回True
。使用異常處理對您的任務更好,並且使您的代碼更具可讀性,因爲如果用戶沒有輸入整數,並且這是語句的初始意圖,那麼您會認爲它是錯誤的。
使用方法ISDIGIT()
試試這個:
A = input("How old are you:")
if A.isdigit() :
print ("you are",A,"years old that's awesome")
else:
print("error! type numbers only! ")
exit()
(如果有人編輯了你的帖子,你應該等待他們在隊列中被批准,如果你同意,或者如果你不同意,可以編輯)我們已經通過了這5次,你的帖子仍然沒有正確格式化) –
@ MatthewCiaramitaro,供參考:問題或答案的作者可以單方面批准或拒絕建議的編輯。因此,他們不需要等待編輯被其他人審閱。事實上,他們可以選擇單方面批准或拒絕編輯,即使其在審覈隊列中被批准或拒絕後也是如此。 – Makyen
今後請解釋那種你得到錯誤的。 –