1. Single Return Value:
def add_numbers(a, b):
result = a + b
return result
sum_result = add_numbers(3, 4)
print(sum_result) # Output: 7
#clcoding.com
7
2. Multiple Return Values:
def operate_numbers(a, b):
addition = a + b
subtraction = a - b
multiplication = a * b
return addition, subtraction, multiplication
result_tuple = operate_numbers(5, 3)
print(result_tuple)
# Output: (8, 2, 15)
# Unpack the tuple
add_result, sub_result, mul_result = operate_numbers(5, 3)
print(add_result, sub_result, mul_result)
# Output: 8 2 15
#clcoding.com
(8, 2, 15)
8 2 15
3. Returning a Dictionary :
def get_person_info(name, age):
person_info = {'Name': name, 'Age': age}
return person_info
info_dict = get_person_info('John', 30)
print(info_dict)
# Output: {'Name': 'John', 'Age': 30}
#clcoding.com
{'Name': 'John', 'Age': 30}
4. Returning None:
def simple_function():
print("This function does something")
result = simple_function()
print(result) # Output: None
#clcoding.com
This function does something
None
5. Returning Early:
def divide(a, b):
if b == 0:
print("Cannot divide by zero.")
return # Exit the function early
result = a / b
return result
result = divide(8, 2)
print(result) # Output: 4.0
#clcoding.com
4.0
0 Comments:
Post a Comment