Python 在功能/输入验证方面有问题

Python 在功能/输入验证方面有问题,python,validation,Python,Validation,我正在为一个家庭作业编写一些代码,我必须把文件中的数字记下来,计算所有数字的总和,平均数以及有多少行。这就是我到目前为止想到的 invalidEntry= True #输入验证 while(无效): 我一直收到except函数的语法错误,我不确定是否正确设置了输入验证。任何帮助都将不胜感激。请尝试: except Exception as err: 尝试此操作,为您修复了一些错误: import os total = 0 lines = 0 # Input the file IfValid

我正在为一个家庭作业编写一些代码,我必须把文件中的数字记下来,计算所有数字的总和,平均数以及有多少行。这就是我到目前为止想到的

invalidEntry= True
#输入验证

while(无效):

我一直收到except函数的语法错误,我不确定是否正确设置了输入验证。任何帮助都将不胜感激。

请尝试:

except Exception as err:

尝试此操作,为您修复了一些错误:

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)

尝试和例外应该有相同的缩进。谢谢!现在,我该如何让他们在一个循环中,直到他们输入一个有效的条目,然后程序的其余部分将执行。编辑我的代码,基本上我把它放在一个while循环中,当他们输入一个有效的条目时,它就会停止。我很感激你的编辑,但是我们不允许使用break语句,老师说这是一个糟糕的做法,这就是为什么我使用了“invalidEntry=True”部分来尝试形成一个循环,但是我不确定如何正确地执行此操作。现在检查最新编辑,取出中断语句谢谢。如果可以的话,我会支持你的答案,它真的帮了我的忙。再次感谢你。
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)