我希望在Python函数中定义两个变量,并将它们明确地定义为浮点数。但是,当我尝试在函数参数中定义它们时,它会显示语法错误。
请帮我获得所需的输出。
这是代码:
def add(float (x) , float (y)) :
z = (x+y)
return (print ("The required Sum is: ", z))
add (5, 8)
我希望在Python函数中定义两个变量,并将它们明确地定义为浮点数。但是,当我尝试在函数参数中定义它们时,它会显示语法错误。
请帮我获得所需的输出。
这是代码:
def add(float (x) , float (y)) :
z = (x+y)
return (print ("The required Sum is: ", z))
add (5, 8)
Python是一种强类型的动态语言,它将类型与值关联,而不是名称。如果您想要强制调用者提供特定类型的数据,则唯一的方法是在函数内部添加显式检查。
最近,这门语言中添加了类型注释,现在可以编写语法正确的函数说明,包括参数和返回值的类型。对于您的示例,注释版本如下:
def add(x: float, y: float) -> float:
return x+y
请注意,这只是语法。Python解释器不会执行其中的任何操作。有一些外部工具,如mypy
可以帮助你实现目标,它们正在迅速成为语言的重要组成部分(尽管人们希望它们仍然是可选的,考虑到存在大量无类型代码的语料库)。
注释在像pydantic
这样的工具中发现了比最初预期更广泛的用途,它们用于执行数据验证。这支持了利用(例如)FastAPI服务器开发新的有趣范例,展示了提高Web编码生产力的巨大潜力。
你可以检查函数提供的实例是否与你想要的类型相符!
def add(x: float, y: float) -> float:
if not isinstance(x, float):
raise TypeError("x and y variables not of type float")
将函数z = float(x+y)
更改为z = float(x)+ float(y)
此时我们假设我们只是将数字相加。
让我们确保我们始终使用浮点数进行计算。在将它们相加之前,将参数转换为浮点数。您可以使用float()函数来完成这个操作。
好的,让我们确保无论输入什么,它都被转换为浮点数。
def add(x, y):
z = float(x)+ float(y)
print "The required Sum is: {}".format(z)
return z
add (5, 8)
但是如果a和b是字符串呢?需要注意一下。
def add(x, y)
try:
a = float(x)
b = float(y)
except ValueError:
return None
else:
return True
def addSum(x,y):
return x+y
addSum(2.2, 5.6)
7.8
addSum(float(2), float(5))
7.0
addSum(2, 5)
7
addSum("Hello ", "World!!")
'Hello World'
我会使用assert isinstance
#!/usr/bin/env python3
import sys
def this_add(x: float, y: float):
assert isinstance(x, float), f"[e] {x} should be a float and it is {type(x)}"
assert isinstance(y, float), f"[e] {y} should be a float and it is {type(y)}"
z = (x+y)
return z
print(f"The required Sum is: {this_add(5.2, 8.9)}")
import unittest
class TestStringMethods(unittest.TestCase):
def test_int(self):
self.assertRaises(AssertionError, this_add, 5, 8)
def test_float(self):
self.assertEqual(14.0, this_add(5.1, 8.9) )
def test_float_and_int(self):
self.assertRaises(AssertionError, this_add, 5.1, 8)
def test_int_and_float(self):
self.assertRaises(AssertionError, this_add, 5, 8.9)
def test_tuple(self):
self.assertRaises(AssertionError, this_add, (5.1, 8.9), 0)
def test_string(self):
self.assertRaises(AssertionError, this_add, "5.1", "8.9")
unittest.main()