python - 遇到异常功能/输入验证问题
问题描述
我正在为家庭作业编写一些代码,我必须在文件中获取数字,计算它们的总和,平均值以及有多少行。这是我到目前为止想出的
invalidEntry= True
#输入验证
而(无效条目):
try:
total = 0
lines = 0
Validate= input("Please enter the name of the text file. : ")
if Validate ==("Random.txt") :
red= open( 'Random.txt', 'r')
for count in red:
strip = line.strip("\n")
lines += 1
average = total/200
total = total + int(count)
print("The number of lines is : ",lines)
print ("The total sum is : " ,total)
print("The average is :" , average
invalidEntry= False
except:
print("This isn't a valid file!")
我不断收到 except 函数的语法错误,我不确定我是否正确设置了输入验证。任何帮助,将不胜感激。
解决方案
试试这个,为你修复了一些错误:
import os
total = 0
lines = 0
# Input the file
IfValidate = False
while IfValidate == False:
validate = input("Please enter the name of the text file: ")
if os.path.isfile(validate) == True:
IfValidate = True
# Open the file
f = open(validate, 'r')
# Read every line and make it a list
f = f.readlines()
for line in f:
# Strip of \n
strip = line.strip("\n")
# Make the number a number
num = int(strip)
lines += 1
average = total / 200
total = total + int(num)
print("The number of lines is : ", lines)
print ("The total sum is : " , total)
print("The average is :" , average)
推荐阅读
- mysql - 如何将 JSON 数据添加或合并到现有 MySQL 行的 JSON 字段中?
- ios - 成为第一响应者时,标题视图中的搜索栏不再居中
- augmented-reality - 如何在 ar.js 中不使用任何标记插入对象
- html - 启用严格的 MIME 检查错误
- swift - Swift 除法“/”运算符不工作还是我错过了什么?
- javascript - 将一串字符串拆分为 2 个分隔符
- indy - Delphi 和 Walmart 批量 API 上传 - 内部服务器错误
- android - 启动画面后如何停止黑屏?
- angular - Angular 4:ngFor内部html不起作用
- javascript - 如何用圆圈图标制作剑道图图例?