Issue
I'm building a simple guessing game in Python and need to display an "Invalid entry" message when the user inputs anything other than an integer. I'm facing a syntax error and am unsure of the correct approach to validate integer input.
Here's the part of my code related to handling the input:
import random
while True:
hidden = random.randrange(1, 5)
try:
guess = int(input("Guess a number between 1 and 5: "))
except ValueError:
print("Invalid Entry. Please enter an integer between 1 and 5.")
continue
# Rest of the guessing logic...
I've attempted to use an if statement to check if the input is an integer, but I'm encountering a syntax error. Here's the error I'm getting:
SyntaxError: invalid syntax
How can I correctly check if the user's input is an integer and prompt an "Invalid entry" message for non-integer inputs?
Are there any best practices in Python for handling this type of input validation?
Solution
If you really want to verify that the user entry is an int, you want to keep the input in string form. Then write a small function to test the input. Here, I'll use a list comprehension and the string join and isdigit methods, to ensure the user has only entered digits 0-9 in the string, i.e. then this function returns True (else False) (*modified as per Jack Taylor comment below, also for s = '' case):
def testForInt(s):
if s:
try:
_ = s.encode('ascii')
except UnicodeEncodeError:
return False
test = ''.join([x for x in s if x.isdigit()])
return (test == s)
else:
return False
If you want to sandbox the user entirely, wrap it in a loop like this:
acceptable = False
while not acceptable:
entry = input("Enter an int: ")
if testForInt(entry):
entry = int(entry)
acceptable = True
else:
print("Invalid Entry")
If you want a simpler version with no function call(see Jack Taylor comment), this works too:
acceptable = False
while not acceptable:
entry = input("Enter an int: ")
try:
entry = int(entry)
acceptable = True
except ValueError as e:
print(f"Failed due to {str(e)}")
Now you've got what you know is an int, with no worries. This kind of approach to verifying user entry saves many headaches if consistently implemented. See SQL injection etc.
Answered By - neutrino_logic
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.