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

2024-09-21 03:26:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我的任务是为小学生做一个小测验。它问他们随机产生的问题,然后输出他们的结果。这个程序在那之前运行得很好。对于我的任务,我必须将用户的“用户名”和“正确答案”存储到.txt文件中。这个程序似乎可以工作,但没有任何内容存储在“classScores.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))

Tags: 文件import程序txtformatisusernamerandom
2条回答
with open("classCores.txt","a+") as f:
    f.write("{}:{}".format(username,correctAnswers))

a+模式打开,以避免覆盖文件。问题是在你的代码中,你忘记了close你的文件。但是,我建议您使用with open()方法,这比open()要好得多。

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.

您的代码将正确地写入该文件,但在完成后关闭该文件是一种良好的做法。正如安蒂·哈帕拉在评论中指出的,你应该这样做:

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

一般来说,初学者的规则是:

Never, ever use 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'
))

相关问题 更多 >

    热门问题