DEV Community

sridhar n
sridhar n

Posted on

Python Day 8 – Pure vs Impure Functions, Local vs Global

Today we looked at pure and impure functions, and at where variables actually live.

Pure function

def spend_for_shopping(amount):
    total = 10000
    total = total - amount
    return total

print(spend_for_shopping(1200))   # 8800, every single time
Enter fullscreen mode Exit fullscreen mode

A pure function:

  1. Always gives the same output for the same input
  2. Doesn't change anything outside itself

Impure function

total = 10000

def eat_outside(amount):
    return total - amount

total = eat_outside(300)
print(total)   # 9700
total = eat_outside(300)
print(total)   # 9400
Enter fullscreen mode Exit fullscreen mode

Same input (300), different output each time, because the function depends on total, which lives outside it and keeps changing.

Another thing I didn't expect: printing counts as a side effect too.

def display(no):
    print(no + 10)
Enter fullscreen mode Exit fullscreen mode

It changes the outside world (your screen), so technically it's impure. Same goes for anything that uses the current time:

from datetime import datetime

def display_time():
    print("Current Time =", datetime.now().strftime("%H:%M:%S"))
Enter fullscreen mode Exit fullscreen mode

Call it twice and you get two different outputs.

Local vs global variables

Local: declared inside a function (parameters count too). It only exists inside that function.

def eat(amount):
    total = 500         # local
    return total - amount
Enter fullscreen mode Exit fullscreen mode

Global: declared outside any function. Every function can read it.

total = 100000          # global
def eat(amount):
    return total - amount
Enter fullscreen mode Exit fullscreen mode

Try this:

total = 100
def check(no1):
    print(total - no1)

check(10)      # 90
print(total)   # 100
print(no1)     # NameError: no1 is local to check()
Enter fullscreen mode Exit fullscreen mode

The global keyword

If you want to modify a global variable inside a function, you need global:

total = 100
def spend(amount):
    global total
    total = total - amount

spend(30)
print(total)   # 70
Enter fullscreen mode Exit fullscreen mode

Without global, Python assumes you're creating a new local variable.

Top comments (0)