python - 如何将用户输入数据写入外部文本文件?
问题描述
我希望能够获取用户输入的测试分数并写入外部文本文件。然后让应用程序从 中读取值并计算平均值。但是,我不确定如何在循环和函数中实现 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()
它返回它的 value counter
,它跟踪输入了多少值, to calculate_average()
,然后逐行读取文件直到counter
变为 0,这意味着它即将读取单词“stop”(它允许通过 'and 识别 EOF ' 在 if 语句中),执行计算并返回其值。
def write_file():
#Variables
counter = 0
file = open("Scores.txt", "w")
while True:
#User Input and Variable to stop loop
inpt = input("Enter score: ")
file.write(inpt + "\n")
if inpt.lower()== 'stop':
file.close()
break
counter += 1
return counter
def calculate_average(counter):
total = 0
total_quiz = counter
scores = open("Scores.txt", "r")
s = ""
try:
while counter > 0 and s != 'stop':
s = int(scores.readline())
if int(s) in range(1,101):
total += int(s)
counter -= 1
else:
print("Invalid data in file.")
except ValueError:
print("Invalid data found")
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 = calculate_average(write_file())
displayAverage(total, total_quiz)
#Run Main Function
main()
注意:文件最初是在写入模式下创建的,每次都会覆盖文件,因此您永远不需要新文件。如果您想保留记录,您可能希望将其更改为追加,但您需要管理从旧输入中提取正确的行。
一点也不漂亮,但应该让您了解如何完成您的目标。
推荐阅读
- css - 有没有办法将父选择器($)保存为 SCSS 中的变量?
- amazon-web-services - Hibernate EC2 实例:它真的会冻结操作系统吗?
- angular - 无法在数字上创建属性“回调”-Angular 9 中的 jsPDF
- python - Python 从 4 个点创建一个椭圆
- firebase - 部署错误 Cloud Functions - Firebase 部署
- vba - 如何在 Excel VBA 中使用名为 Sub 的变量传递 Vlookup 的第一个参数
- ansible - 有没有办法在 Ansible 清单文件中为一台服务器提到多个标签
- javascript - 条件滚动条不适用于 chrome
- java - Open GL中体素模型的纹理映射
- javascript - 在反应 useState 挂钩中将对象推送到数组