在Python中,`return`语句用于从函数中返回一个值。以下是`return`语句的一些用法:
1. 返回单个值:
def add(a, b):
return a + b
2. 返回多个值:
def divide(a, b):
quotient = a // b
remainder = a % b
return quotient, remainder
3. 返回空值(`None`):
def print_hello():
print("Hello")
4. 提前结束函数的执行:
def linear_search(value, lst):
for i in range(len(lst)):
if lst[i] == value:
return i
5. 函数没有`return`语句时,默认返回`None`:
def greet():
print("Hello, World!")
def get_user_info():
return {"name": "John", "age": 30, "city": "New York"}
当函数执行到`return`语句时,它会立即停止执行,并将指定的值返回给调用函数的地方。如果函数中没有`return`语句,或者`return`语句没有跟任何值,那么函数将返回`None`