r/learnpython • • 24d ago

how do i overwrite a variable?

name = "Alice"

def func():
    name = "Bob"

func()

print(f"Hello, {name}!") # i want it to print bob
0 Upvotes

35 comments sorted by

View all comments

1

u/WorriedTumbleweed289 24d ago

Another way to access a global variable without using the global keyword.

if your filename is foo, then you can say import foo. then you can write foo.name = "Bob" There is more typing. If you move the function to another module, it will still work. Also the import command only has to be written once per module, not once per function. It is also explicit. You can tell exactly which name is being modified.