For a practice problem in my homework, i'm making a guessing game that starts off by asking for a number. I'm trying to implement a way that prints "invalid input" when given a string, but i get an error message. here is my code:
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"))
I get this message when I put in a string such as
hello/System/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 /Users/bob/PycharmProjects/untitled/warmup/__init__.py
give me 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
You need to use raw_input for python2, input tries to evaluate the string so it looks for a variable called name and errors as there is no variable called name defined anywhere. You should never use input in python2, it is equivalent to eval(raw_input()) which has obvious security risks.
So to spell it out more clearly, don't use input to take input from a user in python2, use raw_input() and in your case take the raw_input using a try/except catching a ValueError.
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!")
The fact you are just cheking for 1,2 or 3 means you could also just do the casting after you confirm:
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!")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With