DEV Community

yugalakshmi
yugalakshmi

Posted on

Pure Function and Impure Function

Pure Function

A pure function gives the same output for the same input. It does not change external data.

Example:

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

print(add(10, 20))

Output:

30

Impure Function

An impure function depends on or changes external data or produces side effects.

Example:

total = 100

def add(amount):
global total
total = total + amount

add(50)
print(total)

Output:

150

Here, the function changes the global variable total, so it is an impure function.

Top comments (0)