Return Statements
Python tutorial · PySpark.in
Return Statements
The return statement in Python is used to send a value from a function back to the calling statement. It also terminates the execution of the function and transfers program control back to the caller. If a function does not contain a return statement, it returns None by default.
PURPOSE OF RETURN STATEMENT
- To send computed results from a function
- To pass output back to the calling program
- To allow reuse of function results
- To terminate function execution explicitly
SYNTAX OF RETURN STATEMENT
```
Hide
return expression
```
WORKING OF RETURN STATEMENT (INTERNAL FLOW)
- Function execution reaches the return statement
- The expression after return is evaluated
- The evaluated value is sent back to the caller
- Function execution stops immediately
- Control returns to the calling statement
TYPES OF RETURN STATEMENTS
1. Returning a Single Value
Example
```
def square(n):
return n * n
result = square(5)
print(result)
```
Explanation
- The function computes the square of a number
- The computed value is returned
- The returned value is stored in result
2. Returning Multiple Values
Python allows a function to return multiple values by packing them into a tuple.
Example
```
def calculate(a, b):
return a + b, a - b
x, y = calculate(10, 5)
```
Explanation
- Two values are returned
- Python internally returns a tuple
- Tuple is unpacked into x and y
3. Returning No Value
If a function does not explicitly return a value, Python returns None automatically.
Example
```
def show():
print("Hello")
result = show()
print(result)
```
MULTIPLE RETURN STATEMENTS
A function may contain more than one return statement, but only one return statement is executed depending on the flow of control.
Example
```
def check(num):
if num > 0:
return "Positive"
else:
return "Negative"
```
RETURN VS PRINT STATEMENT
Return Statement | Print Statement |
|---|---|
Sends value back to caller | Displays value on screen |
Used for computation | Used for output only |
Terminates function execution | Does not terminate function |
Value can be reused | Value cannot be reused |
RETURN WITH CONDITIONAL STATEMENTS
```
def even_odd(n):
if n % 2 == 0:
return "Even"
return "Odd"
```
IMPORTANT RULES OF RETURN STATEMENT
- Code after return is never executed
- A function can have multiple return statements
- return without value returns None
- Can return any data type (int, float, list, tuple, object)
More Python tutorials
- What is Python and Why is it used for Data Science and Data Engineering?
- How Does Python Work in the Backend? Internal Working of Python
- Top 30 Python Interview Questions for Data Science
- 3-Month Python Roadmap to Excel in Data Science and Machine Learning
- Python Data Types Explained – A Beginner’s Guide
- test
All tutorials · Try the free PySpark compiler · Practice challenges