Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 2 min read

Python - Return Statement, Pure & Impure Functions

Return Statement The return statement is used inside a function to send a value back to the place where the function was called. Once return is executed, the function stops running, and any code written after it is ign

Return Statement

The return statement is used inside a function to send a value back to the place where the function was called. Once return is executed, the function stops running, and any code written after it is ignored. If no value is returned, Python automatically returns None.

Example:

`def add(a, b):
return a + b

result = add(10, 20)
print(result)`

Output:

30

Explanation:

  • def is used to define a function.
  • add() is the function name.
  • a and b are parameters.
  • return a + b sends the sum back.
  • result stores the returned value.

Pure Function:

A pure function is a function that always returns the same output when given the same input, and it does not have any side effects. A side effect is any modification that a function makes to the state of the system or its environment outside of its scope. A pure function is deterministic, meaning that its output is entirely determined by its input.

Here is an example of a pure function:

`function add(a, b) {
return a + b;
}

console.log(add(3, 4));`

Output
7

This function takes two numbers as inputs and returns the sum of them. It is a pure function because it doesn't modify any external state and always returns the same output for the same input.

Impure Function:

An impure function is a function that has side effects or does not always return the same output when given the same input. Side effects can include modifying a global variable, changing the state of an object, or making a network request.

Impure functions are harder to reason about and test because they have hidden dependencies and can produce different outputs for the same input. They are also less flexible and reusable because their behavior can be affected by external factors.

Example of impure functions:

Functions that modify a global variable

let oldValue = 7;
​
function add(newValue) {
return oldValue += newValue;
}
​
console.log(add(5));

Output

12

This function increments the global variable oldValue, which is outside of its scope. As a result, the oldValue variable is modified, and the function has a side effect.

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.