Calling variable defined inside one function from another function

One approach would be to make oneFunction return the word so that you can use oneFunction instead of word in anotherFunction :

def oneFunction(lists):
    category = random.choice(list(lists.keys()))
    return random.choice(lists[category])

    
def anotherFunction():
    for letter in oneFunction(lists):              
        print("_", end=" ")

Another approach is making anotherFunction accept word as a parameter which you can pass from the result of calling oneFunction:

def anotherFunction(words):
    for letter in words:              
        print("_", end=" ")
anotherFunction(oneFunction(lists))

And finally, you could define both of your functions in a class, and make word a member:

class Spam:
    def oneFunction(self, lists):
        category=random.choice(list(lists.keys()))
        self.word=random.choice(lists[category])

    def anotherFunction(self):
        for letter in self.word:              
            print("_", end=" ")

Once you make a class, you have to instantiate an instance and access the member functions:

s = Spam()
s.oneFunction(lists)
s.anotherFunction()

Leave a Comment