使用 Python 3.10.2,它不會識別我輸入的任何整數作為整數。無論是 0、1、2.54、-96 還是任何其他數字,顯然它都不是整數。
我正在做一個簡單的猜謎游戲,我的代碼如下:
userGuess = int(input("Guess a number between 1 and 20: "))
if userGuess != int:
print("Unrecognized input! Did you input a number?")
無論輸入如何,它總是會列印“無法識別的輸入”訊息以及應該為該輸入列印的訊息(“您的猜測不正確!”等)
如果我使用這個type()函式,它會說 userGuess 的型別是-1。這也僅在用戶輸入數字時發生,而不是在數字是預先確定的情況下發生。
uj5u.com熱心網友回復:
如果要檢查輸入是否不是數字,則應在將輸入轉換為int. 您可以使用 . 檢查字串是否僅包含數字.isnumeric。就像是:
userGuess = input("Guess a number between 1 and 20: ")
if not userGuess.isnumeric():
# Input string is not a number
print("Unrecognized input! Did you input a number?")
else:
# Input is a number, is safe to transform into an int
userGuess = int(userGuess)
這僅在您考慮ints 時才有用。如果您想允許floats(例如:3.14),也許您最好嘗試將值轉換為 afloat并查看它是否失敗:
userGuess = input("Guess a number between 1 and 20: ")
try:
userGuess = float(userGuess)
except ValueError:
# Input string is not a float
print("Unrecognized input! Did you input a number?")
uj5u.com熱心網友回復:
本次檢查:
if userGuess != int:
將永遠為真,因為userGuess永遠不會與型別int本身相同。您要做的是檢查是否userGuess是an 的實體 int:
if isinstance(userGuess, int):
但是,這在這里沒有用,因為這一行:
userGuess = int(input("Guess a number between 1 and 20: "))
將分配一個inttouserGuess或引發一個例外(如果沒有任何東西捕獲它,它將立即結束腳本的執行)。
如果要捕獲例外并提供錯誤,請使用try/except:
try:
userGuess = int(input("Guess a number between 1 and 20: "))
except ValueError:
print("Unrecognized input! Did you input a number?")
請注意,如果您的腳本在此之后繼續,userGuess可能根本沒有為其分配任何值,因此您應該立即結束腳本,因為它不可能繼續(這可能會通過在您嘗試時立即引發另一個例外而發生)使用userGuess),或使用while回圈重試輸入,直到userGuess確實有值。
uj5u.com熱心網友回復:
對不起,我回復很快。這是更新的回復。嘗試將非數字轉換為 int 將導致 ValueError。但是,您可以“捕獲”錯誤并按照以下方式進行回應。
userGuess = input("Guess a number between 1 and 20: ")
try:
userGuess = int(userGuess)
except ValueError:
print("Unrecognized input! Did you input a number?")
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/439650.html
標籤:Python python-3.x
上一篇:在另一個類中檢索變數值
