我的任务是为小学生做一个小测验。它问他们随机产生的问题,然后输出他们的结果。这个程序在那之前运行得很好。对于我的任务,我必须将用户的“用户名”和“正确答案”存储到.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))
以
a+
模式打开,以避免覆盖文件。问题是在你的代码中,你忘记了close
你的文件。但是,我建议您使用with open()
方法,这比open()
要好得多。您的代码将正确地写入该文件,但在完成后关闭该文件是一种良好的做法。正如安蒂·哈帕拉在评论中指出的,你应该这样做:
一般来说,初学者的规则是:
以下是一些更好的选择:
如果定义一个函数,那么使用不带尾随
()
的函数名,那么该函数就是一个值,就像数字1一样,并且该函数可以分配给一个变量——就像任何其他值一样。如果要执行存储在变量中的函数,请在变量名后使用尾随的()
:python还允许您创建匿名(未命名)函数,如下所示:
你为什么要这么做?好吧,它可以使你的代码更紧凑:
但是,事实证明python为您定义了所有这些函数——在
operater module
中。因此,您可以使代码更加紧凑,如下所示:下面是一个完整的示例,其中包含一些其他改进:
相关问题 更多 >
编程相关推荐