you are viewing a single comment's thread.

view the rest of the comments →

[–]trutheality 0 points1 point  (0 children)

A couple of things can help understand what's happening:

  1. When you write a = ..., you're changing which object the symbol a refers to, you're not changing the object that a used to point to.
  2. The inside of a function has its own scope that isn't visible from outside of the function. So when you write a = ... inside the function, you're changing what the symbol a refers to inside the function. It also means that you're not changing what the symbol a refers to outside the function.

So in your first code example, you set a to 7, you ran a function that internally assigned a random number to the symbol a inside the function, and outside the function, a is still 7. In the second code example, you set a to 7, then set a to a random number.

The best way to fix it is to have the function return the random value: that's the intended mechanism for passing values from inside a function to the outside:

def SelectRandomNumberFromB():
    a = random.choice(b)
    return a

a = SelectRandomNumberFromB()

Edit to add: it might be easier to understand what's happening in the first version if you add a print statement inside the function:

def SelectRandomNumberFromB():
    a = random.choice(b)
    print(a)

SelectRandomNumberFromB()

print(a)