Home > Back-end >  Overwrite a global variable
Overwrite a global variable

Time:03-30

I'm starting the basics with , and I didn't get how to update a global variable. The code is:

def spam():
    global eggs
    eggs='spam'
def update_eggs():
    global eggs;eggs='global'
print(eggs)

I wanted to overwrite the "eggs" variable set as "spam" by "global", and I tried the methods in this post: Overwrite global var in one line in Python? But it didn't work. Could you advise please? Thank you in advance! Silvia

CodePudding user response:

You need to call the function for it to execute the code inside it.

eggs = 'something'
def spam():
    global eggs
    eggs='spam'
def update_eggs():
    global eggs;eggs='global'

spam() <-- Call function
print(eggs)

This will (marked with an arrow) call the function spam so it updates eggs to spam. Hope this helps.

Additionally, it looks like you did not define the global variable "eggs". You need to mention eggs = "something here" at the beginning of your code. The "global" command makes it so that defined functions are able to edit the global variable eggs after you define it.

CodePudding user response:

The global keyword allows you to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.

It is good practice to intialize the global variable in the main context before it is referenced.

eggs = "global" # global variable initialized

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

def update_eggs():
    global eggs
    eggs = 'update'

print(eggs)
spam() # updates global eggs variable
print(eggs)
update_eggs() # updates global eggs variable
print(eggs)

Output:

global
spam
update

Calling spam() or update_eggs() both update the global variable eggs.

  • Related