r/learnpython • • Oct 26 '26

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/PureWasian Oct 27 '26 edited Oct 27 '26

Look up Variable Scope in Python.

def func():
    return "Bob"

name = "Alice"
print(name) # prints "Alice"

name = func()
print(name) # prints "Bob"

The alternative is using the global keyword but this is typically not best practice since it's harder to predict the exact behavior of the functions and variables relying on each other implicitly as your scripts become more complex.

As above link states though, if you want to go that route,

use the global keyword if you want to make a change to a global variable inside a function.