Python:在代码的早期验证

时间:2015-01-25 18:09:11

标签: python validation

这是我的代码,是儿童的测验。我需要帮助的是,在代码询问用户的类之后,它应该验证输入是否有效而不是直接进行并显示消息 "抱歉,由于您输入的课程无效,我们无法保存您的数据。" 我试过将整个if,elif和else语句直接移到后面:

users_class = int(input("Which class are you in? (1,2 or 3)"))

但这并没有帮助。任何帮助将不胜感激:)

import time
import random
import math
import operator as op

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

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

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

    correct_result = operation(num1, num2)

    print ("What is {} {} {}?".format(num1, rand_key, num2))
    user_answer= int(input("Your answer: "))

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

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

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

users_class = int(input("Which class are you in? (1,2 or 3)"))

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

correct_answers = 0
num_questions = 10

for i in range(num_questions):
    if test():
        correct_answers +=1

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

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

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

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

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

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

3 个答案:

答案 0 :(得分:0)

您只需要在关于用户所在的类的问题后添加一个额外的条件。通常我们会在这里有一个循环,以便再次询问用户是否输入了无效的响应。

print ("Hi {}! Welcome to the Arithmetic quiz...".format(username))
while True:
    users_class = int(input("Which class are you in? (1,2 or 3)"))
    if users_class in [1, 2, 3]:
        break
    print('Please make sure you enter a class from 1 to 3')

答案 1 :(得分:0)

您应该在input之后立即检查输入是否有效,如下所示:

import sys

users_class = int(input("Which class are you in? (1,2 or 3)"))

if users_class not in {1,2,3}:
    print("Sorry, you must enter either a 1, 2, or 3!")
    sys.exit(1)

请注意,sys.exit(1)调用将退出该程序。

现在,这不是最有效的做事方式。例如,如果用户输入的数字不是数字,int(...)会引发异常,因为它无法将" dog"转换为整数。此外,您可能更喜欢程序继续询问有效输入,而不仅仅是停止和退出。这里有一些代码可以做到这一点:

while True:
    try:
        # try to convert the user's input to an integer
        users_class = 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 users_class 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

print(users_class)

答案 2 :(得分:0)

您需要在询问后检查值是否为1,2或3,因此,您可以在users_class = int(input("Which class are you in? (1,2 or 3)"))之后直接移动if。

correct_answers=0移到if的上方,然后将timeTaken设置为0

这有效:

import time
import random
import math
import operator as op
import sys

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

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

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

    correct_result = operation(num1, num2)

    print ("What is {} {} {}?".format(num1, rand_key, num2))
    user_answer= int(input("Your answer: "))

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

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

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

users_class = int(input("Which class are you in? (1,2 or 3)"))

correct_answers = 0
timeTaken = 0

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

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

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

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

num_questions = 10

for i in range(num_questions):
    if test():
        correct_answers +=1

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

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

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

如果它无效,请退出sys,否则按当前代码继续。