python新手,有人可以告诉我为什么以下代码会抛出错误?并建议我修复
def cel_to_fahr(c):
if c < -273.15:
return "physical matter can reach only till -273.15"
else:
f = c * 9/5 + 32
return f
temp = open("tempr.txt")
tempr = temp.read()
tempr = tempr.splitlines()
for t in tempr:
print(cel_to_fahr(t))
文件内容:
10
-20
-289
100
错误:
Traceback (most recent call last):
File "cel_to_fahr.py", line 41, in <module>
print(cel_to_fahr(t))
File "cel_to_fahr.py", line 29, in cel_to_fahr
if c < -273.15:
TypeError: '<' not supported between instances of 'str' and 'float'
答案 0 :(得分:1)
这是非常基本的python。您可以阅读有关编写和读取文件的更多信息。 Python中常见的实践是使用... open。这将确保您在之后关闭该文件。考虑这个例子(可行)与...打开。它还会创建文件。
with open('tempr.txt','w') as f:
f.write('10\n-20\n-289\n100')
def cel_to_fahr(c):
if c < -273.15:
return "physical matter can reach only till -273.15"
else:
return c * 9/5 + 32
with open('tempr.txt') as f:
tempr = [float(i) for i in f.read().split('\n')]
for t in tempr:
print(cel_to_fahr(t))
答案 1 :(得分:1)
已经给出了很好的答案,如果意外地使用字符串,下面将转换为float。另请参阅评论/提示:
# use type hinting to indicate what type of args should be used
def cel_to_fahr(c: float) -> float:
# use doc string to describe your function
"""
usage: a = cel_to_fahr(x)
x = degrees celcius (pos/neg) as float
a = return degrees fahrenheit (pos/neg) as float
Will raise ValueError when x < -273.15
"""
# you can change to float if it is not float or int to begin with
c = c if isinstance(c, (float, int)) else float(c)
# check if c is indeed 0 K (-273.15 C) or up
if c >= -273.15:
return c * 9/5 + 32
# Errors should never pass silently.
# Unless explicitly silenced.
raise ValueError('Physical matter can reach only till -273.15')
答案 2 :(得分:0)
您正在将字符串与浮点数进行比较,请尝试以下方法:
def cel_to_fahr(c):
if c < -273.15:
return "physical matter can reach only till -273.15"
else:
f = c * 9/5 + 32
return f
temp = open("tempr.txt")
tempr = temp.read()
tempr = tempr.splitlines()
for t in tempr:
print(cel_to_fahr(float(t)))
假设您的文件中只有浮动。
从文件中读取的数据将被读取为字符串,直到您投射它们为止。
如果您不确定数据的格式,可以使用try / catch逻辑。但是对于你的文件中所有数据都知道的简单问题,这将是一种过度的。