-1

I have a function test1() and in this function, there is a variable w which is a randomly generated element from a list l. I want to use the value of w in another function test2, but keep the value it generated in test1. my current code is:

import random
def test1 ():
    l = [1,2,3]
    w = random.choice(l)
    print(w)


def test2 ():
    w = test1()
    print(w)


test1()
test2()

with the current code, I get two different values for the variable w, I want its value to be randomly generated once, then be able to use that value across different functions.

1
  • Please repeat your instructional materials on using functions. Pay special attention to how you return a value. Commented Apr 7, 2020 at 17:57

1 Answer 1

1

Test1 doesn't return anything, you have to return w and if you want always the same value you can set a seed:

import random
random.seed(42)
def test1 ():
    l = [1,2,3]
    w = random.choice(l)
    print(w)
    return w


def test2 ():
    w = test1()
    print(w)


test1()
test2()
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, do you mind explaining how seeds work?
Here is an explanation: pynative.com/python-random-seed
one more question, this method generates the same number each time but say that I wanted a different number each time but I want it to stay the same when used in different functions. For example, w takes the value of 2, now when I use w its value is 2. If i run this again w could be 1 so when I use w in this instance it remains as 1. Hope that makes sense.
No, that can't be done because you are using the random package. If you want you have to generate a list with random values and pass to another value of the list each time but if you want that you have to ask another question
could you show me a simple example?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.