How Do I Check If The User Has Entered A Number?
I making a quiz program using Python 3. I'm trying to implement checks so that if the user enters a string, the console won't spit out errors. The code I've put in doesn't work, an
Solution 1:
You need to catch the exception already in the first if
clause. For example:
for _ inrange(num_of_q):
num1=random.randint(0,10)
num2=random.randint(1,10)
op,symbol=random.choice(operation)
print("What is",num1,symbol,num2,"?")
try:
outcome = int(input())
except ValueError:
print("That's not a number!")
else:
if outcome == op(num1, num2):
print("Correct")
score += 1else:
print("Incorrect")
I've also removed the val = int(input())
clause - it seems to serve no purpose.
EDIT
If you want to give the user more than one chance to answer the question, you can embed the entire thing in a while loop:
for _ inrange(num_of_q):
num1=random.randint(0,10)
num2=random.randint(1,10)
op,symbol=random.choice(operation)
whileTrue:
print("What is",num1,symbol,num2,"?")
try:
outcome = int(input())
except ValueError:
print("That's not a number!")
else:
if outcome == op(num1, num2):
print("Correct")
score += 1breakelse:
print("Incorrect, please try again")
This will loop eternally until the right answer is given, but you could easily adapt this to keep a count as well to give the user a fixed number of trials.
Solution 2:
Change
print("What is",num1,symbol,num2,"?")
ifint(input()) == op(num1, num2):
to
print("What is",num1,symbol,num2,"?")
user_input = input()
ifnot user_input.isdigit():
print("Please input a number")
# Loop till you have correct input typeelse:
# Carry on
The .isdigit()
method for strings will check if the input is an integer.
This, however, will not work if the input is a float. For that the easiest test would be to attempt to convert it in a try/except block, ie.
user_input = input()
try:
user_input = float(user_input)
except ValueError:
print("Please input a number.")
Post a Comment for "How Do I Check If The User Has Entered A Number?"