Search code examples
pythonfunctionrandomnameerrordefined

Functions that refer to the output of other functions - Python


I've been having trouble getting functions to work that rely on the output of another function. When I run the following code (this is a very simplified version)...

from random import randint

def event():
    if m == 1:
        r = randint(0, 4)
    else:
        r = randint(3, 7)

def random():
    if r == 1:
        print "Test A"
    elif r == 2:
        print "Test B"
    elif r == 3:
        print "Test C"
    elif r == 4:
        print "Test D"
    elif r == 5:
        print "Test E"
    elif r == 6:
        print "Test F"


m = 1
event()
random()

m = 2
event()
random()

m = 3
event()
random()

...I get NameError: global name 'r' is not defined

I need to keep these in separate functions because in my actual code they are very complicated. How can I get random() to recognise the random number generated by event()?


Solution

  • A simple way is to use return and args

    def event():
        if m == 1:
            r = randint(0, 4)
        else:
            r = randint(3, 7)
        return r                        # return variable r here
    
    
    r = event()                         # accept variable r here from event
    random(r)                           # pass it to random function
    
    def random(r)                       # receive r from the caller
        ....                            # Use r as a variable