python:小学算术测验 - 将结果保存为.txt文件

时间:2015-01-21 23:13:56

标签: python

我的任务是为小学生创建一个小测验。它询问他们随机生成的问题然后输出他们的结果。该程序完美地运行到那时为止。对于我的任务,我必须存储用户'用户名'和他们的正确答案'进入a' .txt'文件。该程序似乎有效,但没有任何内容存储在&class; csores.txt'文件。我对编码很新,所以对我很轻松。任何帮助将不胜感激:)

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))

correctAnswers=0
for question_number in range(10):
    if test():
        correctAnswers +=1

print("{}: You got {} answers correct".format(username, correctAnswers))

my_file = open("classScores.txt", "a")
my_file.write("{}:{}".format(username,correctAnswers))

2 个答案:

答案 0 :(得分:4)

my_file = open("classScores.txt", "a")
my_file.write("{}:{}".format(username,correctAnswers))
     

该程序似乎有效,但没有任何内容存储在&class; csores.txt'   文件。

您的代码将正确写入文件 - 但在完成文件后关闭文件是一种很好的做法。正如Antti Haapala在评论中指出的那样,你应该这样做:

with open("classScores.txt", "a") as my_file:  #my_file is automatically closed after execution leaves the body of the with statement
    username = 'Sajjjjid'
    correct_answers = 3

    my_file.write("{}:{}\n".format(username,correct_answers))
  

我对编码很陌生

eval(str(num1) + operation + str(num2))

通常,初学者的规则是:

  

永远不要使用eval()。

以下是一些更好的选择:

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

    def add(x, y):
        return x+y

    def sub(x, y):
        return x-y

    def mult(x, y):
        return x*y

    ops = {
        '+': add,
        '-': sub,
        '*': mult,
    }

    keys = list(ops.keys()) #=> ['+', '*', '-']
    rand_key = random.choice(keys)  #e.g. '*' 
    operation = ops[rand_key]  #e.g. mult

    correct_result = operation(num1, num2)

如果你定义一个函数,那么使用函数名而不是尾随(),那么函数就是一个值,就像数字1一样,函数可以分配给一个变量 - 就像任何一个其他价值。如果要执行存储在变量中的函数,请在变量名后使用尾随()

def func():
    print('hello')

my_var = func
my_var()  #=>hello

python还允许您创建这样的匿名(未命名)函数:

my_func = lambda x, y: x+y
result = my_func(1, 2)
print(result) #=>3

为什么你需要这样做?好吧,它可以使你的代码更紧凑:

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

    ops = {
        '+': lambda x, y: x + y,  #You can define the function right where you want to use it.
        '-': lambda x, y: x - y,
        '*': lambda x, y: x * y,
    }

    keys = list(ops.keys()) ##=> ['+', '*', '-']
    rand_key = random.choice(keys)  #e.g. '*' 
    operation = ops[rand_key]  #e.g. lambda x, y: x*y

    correct_result = operation(num1, num2)

但事实证明,python为你定义了所有这些函数 - 在operater module中。因此,您可以使代码更紧凑,如下所示:

import random
import math
import operator as op

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

    ops = {
        '+': op.add,  #Just like the add() functions defined above
        '-': op.sub,
        '*': op.mul,
    }

    keys = list(ops.keys()) #=> ['+', '*', '-']
    rand_key = random.choice(keys)  #e.g. '-'
    operation = ops[rand_key]  #e.g. op.sub

    correct_result = operation(num1, num2)

以下是一个完整的示例,其中包含其他一些改进:

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)  #e.g. '+' 
    operation = ops[rand_key]  #e.g. op.add

    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 {}! Welcome to the Arithmetic quiz...".format(username))

correct_answers = 0
num_questions = 3

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


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

答案 1 :(得分:-1)

with open("classCores.txt","a+") as f:
    f.write("{}:{}".format(username,correctAnswers))

a+模式打开,以避免覆盖文件。问题在于您的代码,您忘记了close您的文件。不过,我建议您使用with open()方法,该方法优于open()