我有这段代码,无论出于何种原因,它会在执行后返回none
。有谁知道为什么?
def function():
try:
ctr = 0
total = 0
file = open("text.txt", 'r')
while ctr <= 15:
ctr += 1
for line in file:
line = line.strip("\n")
num = float(line)
total += num
average = total / 15
return average
except ValueError:
total = total
答案 0 :(得分:1)
在值错误之后,您没有返回任何内容。
except ValueError:
total = total
return ???
你确定float(line)不是导致可能的ValueError的错误的来源吗?
答案 1 :(得分:0)
放入评论太多了,但这段代码的输出是什么?
def function():
average = 0
try:
ctr = 0
total = 0
file = open("text.txt", 'r')
while ctr <= 15:
ctr += 1
for line in file:
line = line.strip("\n")
num = float(line)
total += num
average = total / 15
return average
except ValueError as e:
total = total #What?
print("Caught ValueError")
return e
except Exception as e:
print("Caught Exception")
return e
print("At the end...")
return False
ve = function()
答案 2 :(得分:0)
如果我了解您要执行的操作,则需要读取文件并计算其中包含的数字的平均值,而忽略包含非数字的任何行。您当前的代码无法正确执行此操作,因为try
和except
的级别太高。你也有两个循环,你可能只需要一个。
尝试在文件内容的单个循环内移动异常处理:
def function():
ctr = 0
total = 0
with open("text.txt", 'r') as file: # a with statement will close the file for you
for line in file: # just one loop
try:
num = float(line) # this may raise an exception!
ctr += 1
total += num
except ValueError: # ignore ValueError exceptions in the loop
pass
if ctr > 0:
average = total / ctr
else:
average = 0 # or maybe raise an exception here, for a file with no numbers?
return average
如果您需要将平均值限制为15个值,则可以在循环中添加ctr
大于15的额外检查。我把那部分遗漏了,因为从你的非工作代码中你不清楚你想要做什么(计算行数或计数?)。