Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何防止除数字以外的任何输入_Python - Fatal编程技术网

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

Python 如何防止除数字以外的任何输入,python,Python,我对编码很陌生。我已经设法产生了这段代码,这是一个小测试的儿童。它工作得很好,我只需要防止孩子们在问数学问题时输入字母或其他字符。应该会出现“请只输入数字”之类的内容。我尝试了各种各样的函数,比如ValueError,但没有成功。任何帮助都将不胜感激 import time import random import math import operator as op def test(): number1 = random.randint(1, 10) number2 = r

我对编码很陌生。我已经设法产生了这段代码,这是一个小测试的儿童。它工作得很好,我只需要防止孩子们在问数学问题时输入字母或其他字符。应该会出现“请只输入数字”之类的内容。我尝试了各种各样的函数,比如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.")

看,在你的代码中:

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!

你是说喜欢吗?我很想知道你在学什么课程;在过去的几周里,我看到了大约30个非常类似的问题。@HughBothwell GCSE,参见例如GCSE评估。您可以使用internet。@Hasiba您可以在internet上进行研究,而不是要求他人编写代码。这是否属于def测试():?@Hasiba:我会在导入
后立即插入它,以便您的其余代码可以使用。不会出现“请输入一个整数值!”。相反,程序结束,出现此错误消息-回溯(最后一次调用):文件“L:/computingCoursework/majorChanges4.py”,第65行,在if test()中:文件“L:/computingCoursework/majorChanges4.py”,第29行,在测试用户_answer=int(输入(“您的答案:”)中)值错误:int()的文本无效以10为基数:“f'@Hasiba:听起来你好像是剪切并粘贴了它的一些部分,而不是使用给定的函数。
int(输入(“您的答案”)
是否仍在
try。。除了ValueError
块之外?因为它应该捕捉到错误,打印消息,然后再次循环。您使用它而不是
int(输入(“您的答案”)
您可能需要非常努力地阅读书籍才能通过任何课程或测试。。。
    userAnswer = get_int("Your answer: ")   # call the function
                                            #  No ValueErrors!