Jane
Jane

Reputation: 35

How to check if user input is a digit

I am making an educational math game and want to make sure that all user inputs are valid i.e. a number. When they enter a letter or symbol a message needs to be displayed saying "Invalid, please try again." Can anybody help me? This is my code:

import random

counter=0
score = 0
incorrect = 0

name=input("What is your name?")
print("Hi",name,",welcome to your math quiz!")

questions = ["10*2","4-2","6+12","6*4","12-5","6+54","1*0","3-6","4+0","65-9"]
answers=["20","2","18","24",'7','60','0','-3','4','56']

idx_questions = list(enumerate(questions))
idx_answers = list(enumerate(answers))

random.shuffle(idx_questions)

counter=0
inputs = []
for idxq, question in idx_questions:
    print("Question",counter+1,":",question)
    ans = input("What is the answer? ")
    counter=counter+1

    inputs.append(ans)
    for idxa, answer in idx_answers:
        if idxq == idxa and ans == answer:
            print("Correct")
            score=score+1
            print("Correct Answers=",score)
            print("Incorrect Answers=",incorrect)

        elif idxq == idxa and ans != answer:
            print("Incorrect. The answer is", answer)
            incorrect=incorrect+1
            print("Correct Answers=",score)
            print("Incorrect Answers=",incorrect)

print("End of quiz")
print(name,"your score is",score,"out of 10")
print(score*10,"/100",score,",%")
counter=0
while counter<10:
    print("Question",counter+1,": Your answer =", inputs[counter])
    counter=counter+1

Upvotes: 0

Views: 2725

Answers (2)

a2mky
a2mky

Reputation: 193

isdigit() checks if the string consists of digits. You can find it here in the Python Docs.

Examples:

string1 = '1234'
string.isdigit()

This returns as True.

string2 = 'abcd'
string.isdigit()

This returns as False.

Upvotes: 0

Nick Brady
Nick Brady

Reputation: 6592

what you're looking for is the isdigit method on the string class.

i.e. https://docs.python.org/3/library/stdtypes.html#str.isdigit

Here is a way you could request a valid number again if the user did not input a valid number:

def get_answer():
    num_str = input("Please enter a number: ").lower()
    if (num_str.isdigit()):
        return num_str
    else:
        print("Invalid, please try again")
        return get_answer()

Hi Jane, the function will essentially keep asking for an input until the user enters a number. All you need to do is get your ans variable with the function, and you're guaranteed it will be a number. I put it all together for you below. I actually had a couple errors in my code (sorry!) that I fixed. Your working code will look like this:

import random

counter=0
score = 0
incorrect = 0

name=input("What is your name?")
print("Hi",name,",welcome to your math quiz!")

questions = ["10*2","4-2","6+12","6*4","12-5","6+54","1*0","3-6","4+0","65-9"]
answers=["20","2","18","24",'7','60','0','-3','4','56']

idx_questions = list(enumerate(questions))
idx_answers = list(enumerate(answers))

random.shuffle(idx_questions)

def get_answer():
    num_str = input("Please enter a number: ").lower()
    if (num_str.isdigit()):
        return num_str
    else:
        print("Invalid, please try again")
        return get_answer()

counter=0
inputs = []
for idxq, question in idx_questions:
    print("Question",counter+1,":",question)
    ans = get_answer()
    counter=counter+1

    inputs.append(ans)
    for idxa, answer in idx_answers:
        if idxq == idxa and ans == answer:
            print("Correct")
            score=score+1
            print("Correct Answers=",score)
            print("Incorrect Answers=",incorrect)

        elif idxq == idxa and ans != answer:
            print("Incorrect. The answer is", answer)
            incorrect=incorrect+1
            print("Correct Answers=",score)
            print("Incorrect Answers=",incorrect)

print("End of quiz")
print(name,"your score is",score,"out of 10")
print(score*10,"/100",score,",%")
counter=0
while counter<10:
    print("Question",counter+1,": Your answer =", inputs[counter])
    counter=counter+1

Please lmk if you have any questions!

Upvotes: 1

Related Questions