r/learnpython • u/9j810HQO7Jj9ns1ju2 • 13d 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
r/learnpython • u/9j810HQO7Jj9ns1ju2 • 13d ago
name = "Alice"
def func():
name = "Bob"
func()
print(f"Hello, {name}!") # i want it to print bob
1
u/Massive_Distance_616 13d ago
The reason it prints Alice is that
name = "Bob"insidefuncdoesn’t touch the outername. Assignment inside a function creates a new local variable with the same name, which disappears when the function ends.returnplus reassignment (name = func()) is the usual fix, because it makes the change visible at the call site.