0

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!

AMC
  • 2,642
  • 7
  • 13
  • 35
Mystic Mods
  • 31
  • 2
  • 4
  • Does this answer your question? [How can I check if a string represents an int, without using try/except?](https://stackoverflow.com/questions/1265665/how-can-i-check-if-a-string-represents-an-int-without-using-try-except) – AMC Oct 13 '20 at 01:01

4 Answers4

2

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.

Assem
  • 11,574
  • 5
  • 59
  • 97
  • Thanks!, I will try to integrate this to my code now. – Mystic Mods Aug 30 '15 at 16:27
  • replace this line `userAnswer= int(input("\nYour answer: "))` with my code – Assem Aug 30 '15 at 16:28
  • ahh u edited it thanks, i was having some problems trying to asapt the code to mine, ill try this. and yes i will mark as Answered. thanks again! – Mystic Mods Aug 30 '15 at 16:43
  • Thanks, This works, it validates the input, however, before the code would say wheather or not the user got their answer Right ot Wrong, need to work on that. any suggestions before i get it? @bigOTHER – Mystic Mods Aug 30 '15 at 16:46
  • @MysticMods dont print anything inside `quiz()`, get her value by calling it and print it when you want – Assem Aug 30 '15 at 17:05
  • @bigOTHER: use `while True:` and `break` instead of `R`. – Daniel Aug 30 '15 at 17:15
  • The validation works, thanks, however in terms of the purpose of my code it doesnt exactly fit in, i need to ask 10 questions and also say weather or not they got the answer right or wrong, if they did get it wrong then the code tells them the right answer, and then moves onto the next question...? Im just going to try a few more things... – Mystic Mods Sep 01 '15 at 10:27
  • @MysticMods you made a question, I answered it.. if you have other questions, ask them and someone willanswer them. this is how it works in stackoverflow, we dont have to do the whole code for you. – Assem Sep 01 '15 at 10:33
  • its ok thanks, ive understood how exactly to validate inputs now thanks to your help. thanks again. @bigOTHER – Mystic Mods Sep 01 '15 at 11:23
1

in Single line :

assert input('Enter Number: ').isdigit()
Zero Days
  • 851
  • 1
  • 11
  • 22
0

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!')
mmachine
  • 896
  • 6
  • 10
-2

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: ")
Martin Evans
  • 45,791
  • 17
  • 81
  • 97