0

I am new to python. Here is a basic example of my issue.

spam='spam'

def change():
    spam='eggs'

change()

print(spam)

This code will print 'spam' to the console. Is there a way to make this work without using return or arguments. Thank you.

  • 1
    put `global spam` in your function, although note this is not always good practise – Chris_Rands Nov 09 '16 at 21:10
  • I just want to reiterate Chris_Rands warning: this approach is usually not the best way. It will make your code difficult to reason about and difficult to maintain. – juanpa.arrivillaga Nov 09 '16 at 21:11
  • The variables in your function should stay in your function. And the inverse is also true, you should always try not to use global variables (if your function needs something, there most often is a way for you not to use a global variable) – Thomas Kowalski Nov 09 '16 at 21:11
  • Thank you, I'll try to only use it when necessary – Cailean Allway Nov 09 '16 at 21:48

2 Answers2

0

Add global spam inside your def to target the variable defined outside of the method definition, or better yet, assign a new value from the result of the method:

spam = "spam"
def change(): return 'eggs'
spam = change() #spam now contains 'eggs'

However if you pass lists or dictionaries, modifying the value inside the method does affect the outside value too but that's a different story. IF you want to try it, use spam=["spam"] and inside the method do spam[0] = 'eggs'. There's no need for globals or assignments outside the method for this case.

Juan Cortés
  • 20,634
  • 8
  • 68
  • 91
0

you can do the following:

spam='spam'

def change():
    global spam
    spam='eggs'

change()

print(spam)
Alex L
  • 1,069
  • 2
  • 18
  • 33