在Python中,定义函数返回值的基本语法是使用`return`关键字,后面跟要返回的表达式。下面是一些关于如何使用Python定义函数返回值的例子:
1. 返回一个值:
```python
def add_numbers(a, b):
sum = a + b
return sum
result = add_numbers(3, 4)
print(result) 输出:7
2. 返回多个值:
```python
def secondvalue(a, b):
c = a + b
return (a, b, c)
x, y, z = secondvalue(1, 2)
print('x:', x, 'y:', y, 'z:', z) 输出:x: 1 y: 2 z: 3
3. 返回函数作为值:
```python
def get_math_func(type):
if type == 'square':
return lambda n: n * n
elif type == 'cube':
return lambda n: n * n * n
else:
return lambda n: 1
for index in range(2, n + 1):
result *= index
return result
math_func = get_math_func('cube')
print(math_func(5)) 输出:125
4. 隐含的`return`语句:
如果函数中没有`return`语句,函数会隐式地返回`None`。
```python
def func(x, y):
num = x + y
print(num)
result = func(1, 2) 输出:3
print(result) 输出:None
5. 指定`return`返回值的函数举例:
```python
def showplus(x):
print(x)
return x + 1
num = showplus(6)
add = num + 2
print(add) 输出:9
以上示例展示了如何在Python中定义函数并指定其返回值。