Using the same variables in different functions in Python

advertisements

I'm trying to use the return function, I'm new to python but it is one of the things I don't seem to understand.

In my assignment I have to put each task in a function to make it easier to read and understand but for example I create a randomly generated number in a function, I then need the same generated number in a different function and I believe the only way this can be done is by returning data. For example here I have a function generating a random number:

def generate():
    import random
    key = random.randint(22, 35)
    print(key)

But if I need to use the variable 'key' again which holds the same random number in a different function, it won't work as it is not defined in the new function.

def generate():
    import random
    key = random.randint(22, 35)
    print(key)

def number():
    sum = key + 33

So how would I return data (if that is what you need to use) for it to work?


The usage of return indicates to your method to 'return' something back to whatever called it. So, what you want to do for example in your method is simply add a return(key):

# Keep your imports at the top of your script. Don't put them inside methods.
import random

def generate():
    key = random.randint(22, 35)
    print(key)
    # return here
    return key

When you call generate, do this:

result_of_generate = generate()

If you are looking to use it in your number method, you can actually simply do this:

def number():
    key = generate()
    sum = key + 33

And if you have to return the sum then, again, make use of that return in the method in similar nature to the generate method.