0

I have this segment of python code. I want to have a global variable called filetext. However, it does not work as intended, I want to modify the filetext variable in the first method and then use this in the second method.

filetext = "x"

def method1():

    filetext = "heyeeh"

def method2():
    print(filetext)

This yields "x". How come, and how can I overcome this?

p3ob2lem
  • 129
  • 2
  • 11

1 Answers1

0

You need to use global here, without which python will create a new copy of variable with the scope limited to that function which is method1() here. Hence your code should be as:

filetext = "x"

def method1():
    global filetext  # added global here
    filetext = "heyeeh"

def method2():
    print filetext

Sample run:

>>> method2()   # print original string
x
>>> method1()   # Updates the value of global string
>>> method2()   # print the updated value of string
heyeeh
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126