Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python:小学算术测验-将结果保存到.txt文件_Python - Fatal编程技术网

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

python:小学算术测验-将结果保存到.txt文件,python,Python,我的任务是为小学生做一个小测验。它向他们随机提出问题,然后输出结果。在那之前,程序运行得非常好。对于我的任务,我必须将用户的“用户名”和他们的“正确答案”存储到a“.txt”文件中。该程序似乎可以运行,但没有任何内容存储在“classScores.txt”文件中。我对编码很陌生,所以对我放松点。任何帮助都将不胜感激:) 在a+模式下打开,以避免覆盖文件。问题在于您的代码中,您忘记了关闭文件。但是,我建议您使用和open()方法,这比open()好得多 该程序似乎可以运行,但没有任何内容存储在“c

我的任务是为小学生做一个小测验。它向他们随机提出问题,然后输出结果。在那之前,程序运行得非常好。对于我的任务,我必须将用户的“用户名”和他们的“正确答案”存储到a“.txt”文件中。该程序似乎可以运行,但没有任何内容存储在“classScores.txt”文件中。我对编码很陌生,所以对我放松点。任何帮助都将不胜感激:)

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

该程序似乎可以运行,但没有任何内容存储在“classScores.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()

以下是一些更好的选择:

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
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)
你为什么要这么做?它可以使您的代码更加紧凑:

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为您定义了所有这些函数——在
操作符模块中。因此,您可以使代码更加紧凑,如下所示:

my_func = lambda x, y: x+y
result = my_func(1, 2)
print(result) #=>3
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'
))

不要这样故意破坏你的问题——无论是对那些花时间帮助你的人,还是对那些可能会觉得有用的未来访客,这都是粗鲁的。
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'
))