I've been tasked with creating a function "make_counter" which takes a number as its only argument. It should return a dictionary containing two functions that can be invoked to increment and decrement the number and then return it.
The behaviour should be as follows:
counter = make_counter(10)
up = counter['up']
down = counter['down']
print(up()) # 11
print(down()) # 10
print(down()) # 9
print(up()) # 10
with these being the answers it gives out.
However I've tried the following:
def make_counter(num):
def up(num = num):
num += 1
return num
def down(num = num):
num -= 1
return num
return {"up": up, "down": down}
counter = make_counter(10)
up = counter["up"]
down = counter["down"]
print(up()) # 11
print(down()) # 9
print(down()) # 9
print(up()) #11
And these are the answers I get instead, ie. it doesn't remember the count.
I don't understand why this exact solution works in JavaScript but the equivalent doesn't work here in Python. And furthermore, why the inner functions in Python require default arguments or they can't "see" what num is from the parent function outside. Any help would be appreciated.