[英]Python: input accepts integer but crashes on a string
對於我的作業中的練習問題,我正在制作一個猜測游戲,首先要求一個數字。 我正在嘗試實現一種在給定字符串時打印“無效輸入”的方法,但是我收到錯誤消息。 這是我的代碼:
def get_input():
'''
Continually prompt the user for a number, 1,2 or 3 until
the user provides a good input. You will need a type conversion.
:return: The users chosen number as an integer
'''
guess=int(input("give me 1,2,3"))
while True:
if guess==1 or guess==2 or guess==3:
return guess
else:
print "Invalid input!"
guess=int(input("give me 1,2,3"))
當我輸入諸如的字符串時,我收到此消息
hello/System/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 /Users/bob/PycharmProjects/untitled/warmup/__init__.py
給我1,2,3hello
Traceback (most recent call last):
File "/Users/bob/PycharmProjects/untitled/warmup/__init__.py", line 51, in <module>
get_input()
File "/Users/bob/PycharmProjects/untitled/warmup/__init__.py", line 43, in get_input
guess=int(input("give me 1,2,3"))
File "<string>", line 1, in <module>
NameError: name 'hello' is not defined
Process finished with exit code 1
你需要對python2使用raw_input
,輸入嘗試評估字符串,以便它查找名為name
和errors的變量,因為在任何地方都沒有名為name
變量。 你永遠不應該在python2中使用input
,它等同於具有明顯安全風險的eval(raw_input())
。
因此,為了更清楚地拼寫它, 不要使用輸入從python2中的用戶獲取輸入,使用raw_input()
,在您的情況下使用try/except
捕獲ValueError
try/except
的raw_input
。
def get_input():
'''
Continually prompt the user for a number, 1,2 or 3 until
the user provides a good input. You will need a type conversion.
:return: The users chosen number as an integer
'''
while True:
try:
guess = int(raw_input("give me 1,2,3"))
if guess in (1, 2, 3):
return guess
except ValueError:
pass
print("Invalid input!")
您只需要為1,2或3進行檢查,這意味着您在確認后也可以進行投射:
def get_input():
'''
Continually prompt the user for a number, 1,2 or 3 until
the user provides a good input. You will need a type conversion.
:return: The users chosen number as an integer
'''
while True:
guess = raw_input("give me 1,2,3")
if guess in ("1", "2", "3"):
return int(guess)
print("Invalid input!")
您應該在轉換為int之前驗證輸入類型:
guess = raw_input("give me 1,2,3")
while True:
if guess == '1' or guess == '2' or guess == '3':
return int(guess)
else:
print "Invalid input!"
guess = raw_input("give me 1,2,3")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.