I have a function:
which when called creates a specified number of discs, so for example:
will create 5 discs.
I then want to use the integer inputted into the create_discs function in a separate function:
In other words I would like disc_int to equal 5 (or whatever number is inputted)
Can anyone help me?
If you want two functions to share state like this, they should be defined as methods of a class.
class Hanoi(object): def __init__(self, num_discs): self.num_discs = num_discs def create_discs(self): # use value of self.num_discs def hanoi(self): # use value of self.num_discs h = Hanoi(5) h.create_discs() h.hanoi()
If you're passing
5 to create_discs, can you do:
num = 5 create_discs(num) hanoi(num)
You could make a closure:
def create_discs(num): # create some discs def hanoi_closure(): # now num is available within this function # do hanoi stuff return return hanoi_closure hanoi = create_discs(5) hanoi()
In this case,
create_discs defined your
hanoi function within itself so that
num was within its scope (automatically, no need to store anything in a
global or a
class!) and it returned the inner function so you could call it later.
create_discs was already supposed to return something, then you could just return a
tuple with what it was returning plus the inner function:
def create_discs(num): # ... return what_it_normally_returns, hanoi_closure create_discs_result, hanoi = create_discs(5) hanoi()