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.
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.
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.
you can do the following:
spam='spam'
def change():
global spam
spam='eggs'
change()
print(spam)