我想能够采取测试分数的用户输入和写入一个外部文本文件。然后让应用程序从中读取值并计算平均值。但是,我不确定如何在循环和函数中实现python语法。我试图利用我的资源更好地了解如何做到这一点,但在理解python如何处理外部文件时遇到了一些困难。此外,在这种情况下,使用append会比write更好吗? 当前语法:
def testAvgCalculation():
#Variables
total = 0
total_quiz = 0
while True:
#User Input and Variable to stop loop
inpt = input("Enter score: ")
if inpt.lower()== 'stop':
break
#Data Validation
try:
if int(inpt) in range(1,101):
total += int(inpt)
total_quiz += 1
else:
print("Score too small or Big")
except ValueError:
print("Not a Number")
return total, total_quiz
def displayAverage(total, total_quiz):
average = total / total_quiz
print('The Average score is: ', format(average, '.2f'))
print('You have entered', total_quiz, 'scores')
#Main Function
def main():
total, total_quiz = testAvgCalculation()
displayAverage(total, total_quiz)
#Run Main Function
main()
这真是骇人听闻,但我试着使用已经存在的东西。我将原始函数的数据验证部分拆分为一个单独的函数。在
main()
中,它将其值counter
返回给calculate_average()
,该值跟踪输入的值,然后逐行读取文件,直到counter
变为0,这意味着它将要读取单词“stop”(它允许通过if语句中的“and”识别EOF),执行计算并返回其值注意:文件最初是在写入模式下创建的,每次都会覆盖该文件,因此您永远不需要新的文件。如果您想保留一条记录,您可能希望将其更改为append,不过您需要设法从旧输入中提取适当的行
一点也不漂亮,但应该给你一个如何实现目标的想法
相关问题 更多 >
编程相关推荐