1

Why aren't the variables below (A,B,C,D) changed when tst is called.

A,B,C = 0,0,0
D = 0

def tst():
    A,B,C = 1,2,3
    D = 4
    print(A,B,C,D)

tst() # tst is called
print(A,B,C,D)

Output:

(1, 2, 3, 4)
(0, 0, 0, 0)
RandomPhobia
  • 4,698
  • 7
  • 25
  • 22

2 Answers2

6

because of Python scoping rules.

in def tst(), you're creating local variables A, B, and C, and assigning them new values.

if you wish to assign to the global A,B, and C values, use the global keyword.

Mike Corcoran
  • 14,072
  • 4
  • 37
  • 49
1

The variables within the tst method are local, that is, they refer to different values that only exist inside scope of that method. Use the keyword global (as in global A,B,C,D) inside tst to fix the behavior. See an example here and the question here.

Community
  • 1
  • 1
Junuxx
  • 14,011
  • 5
  • 41
  • 71