python:数学测验 - 数据未存储

时间:2015-01-22 01:07:06

标签: python

我的任务是为小学生创建一个测验。测验位工作正常。但我必须计算孩子花了多长时间将'用户名''correctAnswers'和'timeTaken'存储到孩子所在的特定班级的.txt文件中。为此,我要求孩子提供他们的班级编号并存储他们的信息。进入专门为该类创建的文件。 我在柜台的问题是:

即使我的代码中有timeTaken = round(etime)

,时间也不会被舍入

未定义raw_input(我不知道如何定义它)

消息“抱歉,由于您输入的课程无效,我们无法保存您的数据。”即使输入了有效的班级编号,也会出现。

我到处搜索但没有运气。任何帮助都将非常感激。

import time
import random
import math

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

    ops = ['+','-','*']
    operation = random.choice(ops)

    num3=int(eval(str(num1) + operation + str(num2)))

    print ("What is {} {} {}?".format(num1, operation, num2))
    userAnswer= int(input("Your answer:"))
    if userAnswer != num3:
        print ("Incorrect. The right answer is {}".format(num3))
        return False
    else:
        print("correct")
        return True

username=input("What is your name?")
print ("Welcome {} to the Arithmetic quiz".format(username))
usersClass = input("Which class are you in? (1,2 or 3)")
raw_input("Press Enter to Start...")
start = time.time()
correctAnswers=0
for question_number in range(10):
    if test():
        correctAnswers +=1

print("{}: You got {} answers correct".format(username, correctAnswers))
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 :(得分:2)

input的返回值是str对象:

>>> usersClass = input("Which class are you in? (1,2 or 3)")
Which class are you in? (1,2 or 3)3
>>> type(usersClass)
<class 'str'>

因此,您对int个对象的后续检查将评估为False(即'3' != 3),从而产生您所看到的内容。

比较用户选择的usersClass的条件需要比较相同的类型以确保相等。这意味着您可以将input的返回值转换为int并继续将usersClassint进行比较,这将满足您的比较,因为您的代码现在已经写入,< / p>

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

或更改条件以将usersClassstr12的{​​{1}}表示进行比较。

3

关于使用Python 3 if usersClass == '1': with open("class1.txt","a+") as f: f.write("{}:Scored {} in {} seconds".format(username,correctAnswers,timeTaken)) ... 遇到的问题,它已重命名为raw_input :(取自What's New in Python 3.0

  

PEP 3111:raw_input()被重命名为input()。也就是说,新的输入()   函数从sys.stdin读取一行并返回尾随   新线剥离。如果输入终止,它会引发EOFError   过早。要获得input()的旧行为,请使用eval(input())。