0

I need to create program code in python that uses a defined variable from a different subprogram using a simple version:

x = 'ham'

def a():
    x = 'cheese'

def b():
    print(x)
a()
b()

How do I get this to save the global variable x as cheese instead of ham?

2 Answers2

0

Whenever you mutate a global variable in a function, you have to explicitly declare that you're using it as a global:

x = 1

def a():
    global x
    x = 4

def b():
    print(x)

a()
b()

Otherwise, a just creates a local variable x that shadows the global.

Claudiu
  • 224,032
  • 165
  • 485
  • 680
  • Nah. The question is asking how to reference a variable defined in another subprogram/function. `x` is globally defined in this case. – Bleeding Fingers Feb 20 '14 at 18:16
0

I'm guessing by subprogram you mean function?

The reason you are getting a 1 instead of a 4 is because x = 1 sets a global variable (in the global scope).

When you do x = 4 inside of a function it creates a local variable (in that function's local scope). Once the function is finished, the local variables are discarded.

When you call b() and it tries to look up the value of x, there is no local variable x (in b's local scope) so it uses the global variable x, which is 1.

If you want a() to modify the global variable x, you have to options:

1) You can just modify the global variable explicitly

def a():
    global x
    x = 4

2) You can return the local varaible and assign it to the global (preferred)

def a():
    x = 4
    return x

x = a()
bj0
  • 7,893
  • 5
  • 38
  • 49