如何防止除数字之外的任何输入

时间:2015-02-01 18:07:41

标签: python

我对编码很陌生。我设法生成了这个代码,这对孩子们来说是一个小小的考验。它工作正常我只需要阻止孩子在问到数学问题时输入字母或其他字符。喜欢"请输入数字"应该出现。我尝试过各种各样的功能,比如ValueError,但没有运气。任何帮助将不胜感激!

import time
import random
import math
import operator as op

def test():
    number1 = random.randint(1, 10)
    number2 = random.randint(1, num1)

    ops = {
        '+': op.add,  
        '-': op.sub,
        '*': op.mul,
        }

    keys = list(ops.keys()) 
    rand_key = random.choice(keys)  
    operation = ops[rand_key]  

    correctResult = operation(number1, number2)

    print ("What is {} {} {}?".format(number1, rand_key, number2))
    userAnswer= int(input("Your answer: "))

    if userAnswer != correctResult:
        print ("Incorrect. The right answer is {}".format(correctResult))
        return False
    else:
        print("Correct!")
        return True

username=input("What is your name?")

print ("Hi {}! Wellcome to the Arithmetic quiz...".format(username))

while True:
    try:
        # try to convert the user's input to an integer
        usersClass = int(input("Which class are you in? (1,2 or 3)"))
    except ValueError:
        # oh no!, the user didn't give us something that could be converted
        # to an int!
        print("Please enter a number!")
    else:
        # Ok, we have an integer... is it 1, 2, or 3?
        if usersClass not in {1,2,3}:
            print("Please enter a number in {1,2,3}!")
        else:
            # the input was 1,2, or 3! break out of the infinite while...
            break

input("Press Enter to Start...")
start = time.time()

correctAnswers = 0
numQuestions = 10

for i in range(numQuestions):
    if test():
        correctAnswers +=1

print("{}: You got {}/{} {} correct.".format(username, correctAnswers,  numQuestions,
'question' if (correctAnswers==1) else 'questions'))

end = time.time()
etime = end - start
timeTaken = round(etime)

print ("You completed the quiz in {} seconds.".format(timeTaken))

if usersClass == 1:
    with open("class1.txt","a+") as f:
        f.write("   {}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))

elif usersClass == 2:
    with open("class2.txt","a+") as f:
        f.write("   {}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))

elif usersClass == 3:
    with open("class3.txt","a+") as f:
        f.write("   {}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))
else:
    print("Sorry, we can not save your data as the class you entered is not valid.")

1 个答案:

答案 0 :(得分:1)

def get_int(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Please enter an integer value!")

看,在你的代码中:

import operator as op

# DEFINE THE `get_int` FUNCTION HERE
#   (in global scope so other functions can call it)

def test():

然后在下面使用它:

    userAnswer = get_int("Your answer: ")   # call the function
                                            #  No ValueErrors!