0% found this document useful (0 votes)
23 views3 pages

Introduction To Return

Uploaded by

astronautahmed5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views3 pages

Introduction To Return

Uploaded by

astronautahmed5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Introduction to return

In Python, the return statement is used within a function to exit the function and optionally pass a
value (or multiple values) back to the caller. When a return statement is encountered, the
function execution stops, and control is returned to the code that called the function. The value
following return (if any) is returned to the caller as the function’s result.

Syntax of return

The syntax for the return statement is simple:

return [expression]

expression is optional. If provided, this is the value that the function returns. If
omitted, the function returns None by default.

Basic Usage of return

1. Returning a Single Value:


A function can return a single value using the return statement.

def add(a, b):


return a + b
result = add(3, 5)
print(result) # Output: 8

2. Returning Multiple Values:


Python allows you to return multiple values from a function by separating them with
commas. Internally, these values are packed into a tuple.
def get_coordinates():
x = 5
y = 10
return x, y
coordinates = get_coordinates()
print(coordinates) # Output: (5, 10)

If you want, you can unpack these values into separate variables:

x, y = get_coordinates()
print(x) # Output: 5
print(y) # Output: 10
3. Returning Early from a Function:
You can use return to exit a function early, even before reaching the end of the
function’s body.

def check_positive(n):
if n <= 0:
return "Not positive"
return "Positive"
print(check_positive(10)) # Output: Positive
print(check_positive(-5)) # Output: Not positive

4. Returning None :
If a function does not explicitly return a value or if you use return without an
expression, Python returns None by default.

def do_nothing():
return
result = do_nothing()
print(result) # Output: None

5. Return and Loops:


You can use return to break out of loops within a function, and it will immediately exit
the function:
def find_even(numbers):
for num in numbers:
if num % 2 == 0:
return num
return "No even numbers found"
print(find_even([1, 3, 5, 8])) # Output: 8
print(find_even([1, 3, 5])) # Output: No even numbers
found

You might also like