首页 > 解决方案 > 遇到异常功能/输入验证问题

问题描述

我正在为家庭作业编写一些代码,我必须在文件中获取数字,计算它们的总和,平均值以及有多少行。这是我到目前为止想出的

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 函数的语法错误,我不确定我是否正确设置了输入验证。任何帮助,将不胜感激。

标签: pythonvalidation

解决方案


试试这个,为你修复了一些错误:

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)

推荐阅读