-3

我正在尝试使用 python 将分数和名称的变量打印到 .txt 文件中。

import random
import csv
import operator
import datetime


now = datetime.datetime.now() ## gets the exact time of when the user begins the test.

def main():
    global myRecord
    myRecord = []
    name = getNames()
    myRecord.append(name)
    record = quiz()


def getNames(): ## this function grabs first and lastname of the user
    firstName = input ("Please enter your first name") ## asks for users name
    surName = input("Please enter your surname") ## asks for users suername
    space = " "
    fullName =  firstName + space +surName ## puts data of name together to  make full name
    print("Hello")
    print (fullName)
    myRecord.append(fullName)
    return fullName ## this is a variable returned to main

def quiz():
    print('Welcome. This is a 10 question math quiz\n')
    score = 0 ## sets score to 0.
    for i in range(10): ## repeats question 10 times
        correct = askQuestion()## if the statement above if correct the program asks a question.
        if correct:
            score += 1## adds one to the score
            print('Correct!\n')## prints correct if the user gets a question correct.
        else:
            print('Incorrect!\n') ## prints incorrect if the user gets a question wrong.
            return 'Your score was {}/10'.format(score)

def randomCalc():
    ops = {'+':operator.add, ## selects one of the three operators
           '-':operator.sub, ## selects one of the three operators
           '*':operator.mul,} ## selects one of the three operators
    num1 = random.randint(0,12)    ## samples a number between 0 and 12
    num2 = random.randint(1,10)   ## zero are not used to stop diving by zero
    op = random.choice(list(ops.keys()))
    answer = ops.get(op)(num1,num2)
    print('What is {} {} {}?\n'.format(num1, op, num2))  ## puts together the num1, the operator and num2 to form question
    return answer

def askQuestion():
    answer = randomCalc()
    guess = float(input())
    return guess == answer

def myfileWrite (myrecord):
    with open('Namescore.txt', 'w') as score:
        score.write(fullName + '\n')




main()

这是它应该询问用户姓名的完整代码,打印 10 道数学问题,然后将时间名称和分数保存到 txt 文件中,如果您可以提供帮助,请非常感谢

4

2 回答 2

2

您的缩进不正确,您从未真正调用过该函数:

with open('Namescore.txt', 'w') as score:
    score.write(fullName + '\n')
于 2015-03-21T14:39:53.510 回答
0

您编写的代码会在您每次运行代码时重新生成文件。我相信这是正确的方法:

with open("Namescore.txt", "a") as file:
    file.write(name, score, "\n")  # I don't know what your vars are called

这将附加到文件而不是重写:)

如果您想按照自己的方式进行操作,正确的方法是:

def writeScore(name, score):
    file = open("Namescore.txt", "a")
    file.write(name, score, "\n")
    file.close()

writeScore("Example Examlpus", 201)
于 2015-03-21T14:41:32.853 回答