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
A pure function:
- Always gives the same output for the same input
- 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
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)
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"))
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
Global: declared outside any function. Every function can read it.
total = 100000 # global
def eat(amount):
return total - amount
Try this:
total = 100
def check(no1):
print(total - no1)
check(10) # 90
print(total) # 100
print(no1) # NameError: no1 is local to check()
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
Without global, Python assumes you're creating a new local variable.
Top comments (0)