简体   繁体   English

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

[英]python: Primary school Arithmetic quiz- saving results to a .txt file

my task is to create a small quiz for primary school children. 我的任务是为小学生创建一个小测验。 It asks them randomly generated questions then outputs their result. 它询问他们随机产生的问题,然后输出结果。 The program works perfectly well up until that point. 到目前为止,该程序运行良好。 For my task I must store the users 'username' and their 'correctAnswers' onto the a '.txt' file. 对于我的任务,我必须将用户“用户名”及其“ correctAnswers”存储到“ .txt”文件中。 The program seems to work but nothing is stored onto 'classScores.txt' file. 该程序似乎可以运行,但是没有任何内容存储到“ classScores.txt”文件中。 Im quite new to coding so go easy on me. 我对编码非常陌生,所以对我轻松一点。 Any help would be appreciated :) 任何帮助,将不胜感激 :)

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))
 my_file = open("classScores.txt", "a") my_file.write("{}:{}".format(username,correctAnswers)) 

The program seems to work but nothing is stored onto 'classScores.txt' file. 该程序似乎可以运行,但是没有任何内容存储到“ classScores.txt”文件中。

Your code will correctly write to the file--but it's good practice to close a file after you are done with it. 您的代码将正确地写入文件-但在完成操作后关闭文件是一种很好的做法。 As pointed out by Antti Haapala in the comments, you should do this: 正如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))

Im quite new to coding 我对编码很陌生

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

Typically, the rule for beginners is: 通常,初学者的规则是:

Never, ever use eval(). 永远不要使用eval()。

Here are some better alternatives: 这里有一些更好的选择:

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)

If you define a function, then use the function name without the trailing () , then the function is a value, just like the number 1, and the function can be assigned to a variable--just like any other value. 如果定义一个函数,则使用不带尾部()的函数名称,则该函数是一个值,就像数字1一样,并且可以将函数分配给变量-就像其他任何值一样。 When you want to execute a function stored in a variable, you use the trailing () after the variable name: 如果要执行存储在变量中的函数,请在变量名称后使用尾随()

def func():
    print('hello')

my_var = func
my_var()  #=>hello

python also lets you create anonymous(unnamed) functions like this: python还允许您创建匿名(未命名)函数,如下所示:

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

Why would you ever need to do that? 为什么您需要这样做? Well, it can make your code more compact: 好吧,它可以使您的代码更紧凑:

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)

But, it turns out that python defines all those functions for you--in the operater module . 但是,事实证明python在operater module为您定义了所有这些功能。 So, you can make your code even more compact, like this: 因此,您可以使代码更加紧凑,如下所示:

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)

Here is a complete example with some other improvements: 这是一个带有其他改进的完整示例:

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'
))
with open("classCores.txt","a+") as f:
    f.write("{}:{}".format(username,correctAnswers))

Opened in a+ mode for avoid overwriting the file. 为避免覆盖文件,以a+模式打开。 The problem is in your codes, you forgot to close your file. 问题出在您的代码中,您忘记了close文件。 However, I suggest you use with open() method which is way better than open() . 但是,我建议您使用with open()方法,该方法比open()更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM