我是Python新手,被分配创建一个简单的函数,将一种温度(C、F、K)转换为另一种温度。足够简单,但是当使用 x 时,默认值设置为 0,作为函数中的输入,我收到“无法将序列乘以‘float’类型的非 int”错误。我似乎无法弄清楚我做错了什么。我的代码,然后错误附在下面。
import warnings
def convTemp(x=0, fro="C", to="F"):
if fro == "C" and to == "F":
x = 1.8 * x + 32
return x
elif fro == "C" and to == "K":
x = x + 273.15
return x
elif fro == "F" and to == "C":
x = x * (5/9)-32
return temp
elif fro == "F" and to == "K":
x = (x * (5/9)-32)+273.15
return x
elif fro == "K" and to == "C":
x = x - 273.15
return x
elif fro == "K" and to == "F":
x = (9/5)*(x - 273.15) + 32
return x
else:
if fro == to:
warnings.warn("Your 'fro' parameter is the same as your 'to' parameter!")
TypeError Traceback (most
recent call last)
<ipython-input-2-e9e7ea7efd49> in <module>
1 assert convTemp(0) == 32
----> 2 assert convTemp([0,10,20]) == [32, 50, 68]
3
<ipython-input-1-a8e50b49bfb6> in convTemp(x, fro, to)
2 def convTemp(x=0, fro="C", to="F"):
3 if fro == "C" and to == "F":
----> 4 x = 1.8 * x + 32
5 return x
6 elif fro == "C" and to == "K":
TypeError: can't multiply sequence by non-int of type 'float'
我尝试通过在函数之前声明 x 具有数字值来解决此问题,并且我还尝试将 x 显式列出为 int、float 和 list。
该错误意味着您正在尝试获取列表或元组并使用非整数值执行乘法函数。为了便于理解,如果您使用整数 n,它将返回该列表 n 次。
例如
[0,1,2]*3
返回 [0,1,2,0,1,2,0,1,2]
。
您的函数定义是:
def convTemp(x=0, fro="C", to="F"):
if fro == "C" and to == "F":
x = 1.8 * x + 32
return x
...
您正在使用以下方式调用断言函数:
assert convTemp([0,10,20]) == [32, 50, 68]
它所做的是将整个数组添加到函数中的
x
中。
如上所述,无法执行
1.8 * [0,10,20]
。
相反,您希望将数组中的每个元素解压到函数调用并返回一个输出数组。那就是:
assert [convTemp(i) for i in [0,10,20]] == [32, 50, 68]
你的第一行通过了,你的第二行失败了。这是因为您的函数是为单个数字而不是数字列表设计的。
如果目的是允许数字列表,则保持函数签名
def convTemp(x=[0], fro='C', to='F')
,然后按照该意图进行构建。
def convTemp(x=[0], fro='C', to='F'):
for i, measurement in enumerate(x):
<your logic here>
x[i] = <converted measurement>
...
return x
如果您确实需要一个同时接受整数或列表的函数,那么您需要更多的逻辑来处理它 - 这是一个奇怪的设计,但可以完成。