Python return statement
Created By: chatGPT
Return statements are used in Python functions to send a result back to the caller. When a function executes a return statement, it terminates its execution and sends the specified value (if any) back to the point where the function was called. If no value is specified, the function returns None by default.
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
In the example above, the function
add
takes two parameters, a
and b
, and returns their sum. When add(5, 3)
is called, the function returns 8
which is then printed.def square(num):
return num * num
print(square(4)) # Output: 16
If you want to return multiple values from a function, you can do so by separating them with commas. Python will pack them into a tuple.
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([1, 2, 3, 4, 5])
print(low, high) # Output: 1 5
You can also return a value from a function based on conditions. For instance, a function can return different results depending on input values.
def check_even_odd(num):
if num % 2 == 0:
return 'Even'
else:
return 'Odd'
print(check_even_odd(10)) # Output: Even
Finally, using a return statement allows for better control over the flow of functions and enhances code readability. By utilizing return statements effectively, you can create modular and clean code.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120