[英]Can't convert strings to int or float
So I was able to fix the first issue with you guys help but now that th program is running without any errors, it's not calculating the average correctly and I'm not sure why.所以我能够在你们的帮助下解决第一个问题,但是现在程序运行没有任何错误,它没有正确计算平均值,我不知道为什么。 Here's what it looks like:
这是它的样子:
def calcAverage():
with open('numbers.dat', 'r') as numbers_file:
numbers = 0
amount = 0
for line in numbers_file:
amount = amount + float(line)
numbers += 1
average = amount / numbers
print("The average of the numbers in the file is:",average)
You're reassigning line
after you check whether line
is empty in the while
.在检查
while
中的line
是否为空后,您正在重新分配line
。 The while
test is testing the previous line in the file. while
测试正在测试文件中的前一行。
So when you get to the end, you read a blank line and try to add it to the amount
, but get an error.所以当你读到最后时,你读到一个空行并尝试将它添加到
amount
,但得到一个错误。
You're also never adding the first line, since you read it before the loop and never add that to amount
.您也永远不会添加第一行,因为您在循环之前阅读了它并且永远不会将其添加到
amount
。
Use a for
loop instead of while
, it will stop automatically when it reaches the end.使用
for
循环而不是while
,它会在到达结束时自动停止。
def calcAverage():
with open('numbers.dat', 'r') as numbers_file:
numbers = 0
amount = 0
for line in numbers_file:
amount = amount + float(line)
numbers += 1
average = amount / numbers
print("The average of the numbers in the file is:",average)
If you do want to use a while
loop, do it like this:如果您确实想使用
while
循环,请这样做:
while True:
line = numbers_file.readline()
if not line:
break
# rest of loop
Error shows that you have empty string in line
.错误显示您在
line
有空字符串。
You can get the same error with float('')
你可以用
float('')
得到同样的错误
You run code in wrong order - you read new line before converting previous line.您以错误的顺序运行代码 - 在转换前一行之前读取新行。
And you should strip line because it still have \\n
你应该剥离线,因为它仍然有
\\n
You need你需要
line = numbers_file.readline()
line = line.strip() # remove `\n` (and `\t` and spaces)
while line != '':
# convert current line
amount = amount + float(line)
numbers += 1
# read next line
line = numbers_file.readline()
line = line.strip() # remove `\n` (and `\t` and spaces)
You could also use for
-loop for this您也可以为此使用
for
-loop
numbers = []
for line in numbers_file:
line = line.strip() # remove `\n` (and `\t` and spaces)
if line:
numbers.append( float(line) )
#else:
# break
average = sum(numbers) / len(numbers)
and this could be reduced to这可以减少到
numbers = [float(line) for line in numbers_file if line.strip() != '']
average = sum(numbers) / len(numbers)
Other answers illustrated how to read a file line-by-line.其他答案说明了如何逐行读取文件。 Some of them dealt with issues like reaching end-of-file (EOF) and invalid input for conversion to float.
其中一些处理诸如到达文件结尾 (EOF) 和用于转换为浮点数的无效输入等问题。
Since any I/O and UI can be expected to give invalid input, I want to stress on validation before processing the input as expected.由于任何 I/O 和 UI 都可能会提供无效输入,因此我想在按预期处理输入之前强调验证。
For each line read from an input console or file alike, you should consider validating.对于从输入控制台或类似文件读取的每一行,您应该考虑进行验证。
float
?float
怎样? (value range, decimal precision) Advice: To make it robust, expect input errors and catch them.建议:为了使其健壮,预期输入错误并捕获它们。
(a) using try-except construct for error-handling in Python: (a) 在 Python 中使用try-except构造进行错误处理:
for line in numbers_file:
try:
amount = amount + float(line)
numbers += 1
except ValueError:
print "Read line was not a float, but: '{}'".format(line)
(b) testing on input ahead: In a more simple way, you could also test manually using basic if
statements like: (b) 提前测试输入:以更简单的方式,您还可以使用基本的
if
语句手动测试,例如:
if line == "": # on empty string received
print("WARNING: read an empty line! This won't be used for calculating average.") # show problem and consequences
continue # stop here and continue with next for-iteration (jump to next line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.