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

2024-10-03 17:20:46 发布

您现在位置: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.")

Tags: thetoinformatinputiftimeis
1条回答
网友
1楼 · 发布于 2024-10-03 17:20:46
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!

相关问题 更多 >