How to validate a users input to Numbers only? - python

I need help validating the input from the (random) questions I ask to make sure that the users input is only a number, rather than letters or any other random character. Also along with the validation there should be an error message notifying the user theyve done something wrong as well as repeat their chance to do the question.
So far the section of my code I need validating is the following:
def quiz():
x = random.randint(1, 10)
y = random.randint(1, 10)
ops = {'+': operator.add,'-': operator.sub,'*': operator.mul}
keys = list(ops.keys())
opt = random.choice(keys)
operation = ops[opt]
answer = operation(x, y)
print ("\nWhat is {} {} {}?".format(x, opt, y))
userAnswer= int(input("\nYour answer: "))
if userAnswer != answer: #validate users answer to correct answer
print ("\nIncorrect. The right answer is",answer,"")
print ("\n============= 8 =============")
return False
else:
print("\nCorrect!")
print ("\n============= 8 =============")
return True
for i in range(questions): #ask 10 questions
if quiz():
score +=1
print("\n{}: You got {}/{} questions correct.".format(name, score, questions,))
Thanks in advance!

Use try...except:
while True:
userAnswer = input("\nYour answer: ")
try:
val = float(userAnswer)
break
except ValueError:
print("That's not a number!")
If you want only integers, use int instead of float.

in Single line :
assert input('Enter Number: ').isdigit()

You may use function validate integer input:
def int_validation(user_Input):
try:
val = int(user_Input)
except ValueError:
print(user_Input,' not an integer!')

It would be good to make a function to accept your input. This can then keep prompting the user until a valid number is entered:
def get_number(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Please enter a number")
You can then change your input line as follows:
userAnswer = get_number("\nYour answer: ")

Related

How to check is an input that is meant to be an integer is empty(in python)?

def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!(Please do not leave this blank)", above=0):
while True:
try:
user_input = int(input(output_message))
if user_input >= above:
return int(user_input)
break
else:
print(error_1.format(above))
except ValueError:
print(error_2)
As you can see here the code is supposed to check if an input is an integer and it is above a certain value which by default is 0, but could be changed.
When the user inputs random letters and symbols it see that there is a value error and returns "Integers only!(Please do not leave this blank)".
I want to be able to check if the user inputs nothing, and in that case only it should output "This is blank/empty", the current way of dealing with this is to not check at all and just say "Integers only!(Please do not leave this blank)", in case there us a value error. I want to be able to be more specific and not just spit all the reasons at once. Can anyone please help me?
Thanks in advance.
You could do something like this :
def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!", above=0, error_3="Please do not leave this blank"):
while True:
user_input = input(output_message)
try:
user_input = int(user_input)
if user_input >= above:
return user_input
break
else:
print(error_1.format(above))
except ValueError:
if(not user_input):
print(error_3)
else:
print(error_2)
I moved the input outside the try/except block to be able to use it in the except ! This worked fine for me, I hope this is what you needed.
You could just break the input and the conversion to int into two steps, like this:
def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!(Please do not leave this blank)", above=0):
while True:
try:
user_input = input(output_message)
if not user_input:
print("Please do not leave this blank")
continue
user_input = int(user_input)
if user_input >= above:
return int(user_input)
break
else:
print(error_1.format(above))
except ValueError:
print(error_2)

How to check if input is digit and in range at the same time? Python

I would like to check if my input is digit and in range(1,3) at the same time and repeat input till I got satisfying answer.
Right now I do this in this way, but the code is quite not clean and easy... Is there a better way to do this?
Maybe with while loop?
def get_main_menu_choice():
ask = True
while ask:
try:
number = int(input('Chose an option from menu: '))
while number not in range(1, 3):
number = int(input('Please pick a number from the list: '))
ask = False
except: # just catch the exceptions you know!
print('Enter a number from the list')
return number
Will be grateful for help.
I guess the most clean way of doing this would be to remove the double loops. But if you want both looping and error handling, you'll end up with somewhat convoluted code no matter what. I'd personally go for:
def get_main_menu_choice():
while True:
try:
number = int(input('Chose an option from menu: '))
if 0 < number < 3:
return number
except (ValueError, TypeError):
pass
def user_number():
# variable initial
number = 'Wrong'
range1 = range(0,10)
within_range = False
while number.isdigit() == False or within_range == False:
number = input("Please enter a number (0-10): ")
# Digit check
if number.isdigit() == False:
print("Sorry that is not a digit!")
# Range check
if number.isdigit() == True:
if int(number) in range1:
within_range = True
else:
within_range = False
return int(number)
print(user_number())
``
see if this works
def get_main_menu_choice():
while True:
try:
number = int(input("choose an option from the menu: "))
if number not in range(1,3):
number = int(input("please pick a number from list: "))
except IndexError:
number = int(input("Enter a number from the list"))
return number
If your integer number is between 1 and 2 (or it is in range(1,3)) it already means it is a digit!
while not (number in range(1, 3)):
which I would simplify to:
while number < 1 or number > 2:
or
while not 0 < number < 3:
A simplified version of your code has try-except around the int(input()) only:
def get_main_menu_choice():
number = 0
while number not in range(1, 3):
try:
number = int(input('Please pick a number from the list: '))
except: # just catch the exceptions you know!
continue # or print a message such as print("Bad choice. Try again...")
return number
If you need to do validation against non-numbers as well you'll have to add a few steps:
def get_main_menu_choice(choices):
while True:
try:
number = int(input('Chose an option from menu: '))
if number in choices:
return number
else:
raise ValueError
except (TypeError, ValueError):
print("Invalid choice. Valid choices: {}".format(str(choices)[1:-1]))
Then you can reuse it for any menu by passing a list of valid choices, e.g. get_main_menu_choice([1, 2]) or get_main_menu_choice(list(range(1, 3))).
I would write it like this:
def get_main_menu_choice(prompt=None, start=1, end=3):
"""Returns a menu option.
Args:
prompt (str): the prompt to display to the user
start (int): the first menu item
end (int): the last menu item
Returns:
int: the menu option selected
"""
prompt = prompt or 'Chose an option from menu: '
ask = True
while ask is True:
number = input(prompt)
ask = False if number.isdigit() and 1 <= int(number) <= 3 else True
return int(number)

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, and I'm not sure how to go about fixing it.
import random
import operator
operation=[
(operator.add, "+"),
(operator.mul, "*"),
(operator.sub, "-")
]
num_of_q=10
score=0
name=input("What is your name? ")
class_num =input("Which class are you in? ")
print(name,", welcome to this maths test!")
for _ in range(num_of_q):
num1=random.randint(0,10)
num2=random.randint(1,10)
op,symbol=random.choice(operation)
print("What is",num1,symbol,num2,"?")
if int(input()) == op(num1, num2):
print("Correct")
score += 1
try:
val = int(input())
except ValueError:
print("That's not a number!")
else:
print("Incorrect")
if num_of_q==10:
print(name,"you got",score,"/",num_of_q)
You need to catch the exception already in the first if clause. For example:
for _ in range(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 += 1
else:
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 _ in range(num_of_q):
num1=random.randint(0,10)
num2=random.randint(1,10)
op,symbol=random.choice(operation)
while True:
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 += 1
break
else:
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.
Change
print("What is",num1,symbol,num2,"?")
if int(input()) == op(num1, num2):
to
print("What is",num1,symbol,num2,"?")
user_input = input()
if not user_input.isdigit():
print("Please input a number")
# Loop till you have correct input type
else:
# 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.")

How to check user input (Python)

I have seen many answers to this question but am looking for something very specific. What I need to accomplish (in pseudo code) is this:
> FOR every ITEM in DICTIONARY, DO:
> PROMPT user for input
> IF input is integer
> SET unique-variable to user input
I'm very new to Python so the code may not be proper, but here is what I have:
def enter_quantity():
for q in menu:
quantities[q] = int(input("How many orders of " + str(q) + "?: "))
So this does everything but evaluate the user input. The problem I'm having is if the input is incorrect, I need to re-prompt them for the same item in the top-level for loop. So if it's asking "How many slices of pizza?" and the user inputs "ten", I want it to say "Sorry that's not a number" and return to the prompt again of "How many slices of pizza?".
Any/all ideas are appreciated. Thanks!
My final solution:
def enter_quantity():
for q in menu:
booltest = False
while booltest == False:
inp = input("How many orders of " + str(q) + "?: ")
try:
int(inp)
booltest = True
except ValueError:
print (inp + " is not a number. Please enter a nermic quantity.")
quantities[q] = int(inp)
You need a while loop with a try/except to verify the input:
def enter_quantity():
for q in menu:
while True:
inp = input("How many orders of {} ?: ".format(q))
try:
inp = int(inp) # try cast to int
break
except ValueError:
# if we get here user entered invalid input so print message and ask again
print("{} is not a number".format(inp))
continue
# out of while so inp is good, update dict
quantities[q] = inp
This bit of code is a little more useful if a menu is added otherwise it crashes at the first hurdle. I also added a dictionary to store the input values.
menu = 'pizza', 'pasta', 'vino'
quantities = {}
def enter_quantity():
for q in menu:
while True:
if q == 'pizza':
inp = input(f"How many slices of {q} ?: ")
elif q == 'pasta':
inp = input(f"How many plates of {q} ?: ")
elif q == 'vino':
inp = input(f"How many glasses of {q} ?: ")
try:
inp = int(inp) # try cast to int
break
except ValueError:
# exception is triggered if invalid input is entered. Print message and ask again
print("{} is not a number".format(inp))
continue
# while loop is OK, update the dictionary
quantities[q] = inp
print(quantities)
Then run the code from this command:
enter_quantity()

I am making a function to detect input types in Python and I can't make it work

So I am making a prime number detector as a project. I’m VERY new to programming and my friend showed me a little python. I want to make a function that detects if the user puts in a number for the input (like 5,28,156,42,63) and if the put in something else (like banana,pants,or cereal) to give them a custom error saying "Invalid Number. Please Try Again" and then looping the program until they put in a number.
Please help me make this work.
def number_checker():
user_number = int(input('Please enter a Number: '))
check = isinstance(user_number, int)
if check == True:
print ('This is a number')
if check == False:
print ('This is not a number')
1) Casting input to int would raise an exception if the input string cannot be converted to int.
user_number = int(input('Please enter a Number: '))
^^^
2) It does not make sense to cross-verify user_number with int instance as it would already be int
3) You can try
def number_checker():
while not input("enter num: ").isdigit():
print("This is not a number")
print("This is a number")
number_checker()
Try following:
def number_checker():
msg = 'Put your number > '
while True:
user_input = input(msg)
correct = user_input.isdigit()
if correct:
print("This is an integer")
return # here you can put int(user_input)
else:
print("This is not an integer")
msg = 'You typed not integer. Try again.> '
if __name__ == '__main__':
number_checker()
And it's also good rule give names for your functions as verbs according to what they do. For this one, I would give, for example def int_input or something.

Categories