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

SYNTAX OF RETURN STATEMENT

```

Hide

return expression

```

WORKING OF RETURN STATEMENT (INTERNAL FLOW)

  1. Function execution reaches the return statement
  2. The expression after return is evaluated
  3. The evaluated value is sent back to the caller
  4. Function execution stops immediately
  5. 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

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

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


More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges