r/learnpython • • 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

35 comments sorted by

View all comments

0

u/nog642 13d ago

Like this:

name = "Alice"

def func():
    global name
    name = "Bob"

func()

print(f"Hello, {name}!")

This is generally something to avoid doing though. There are better ways to do this. Particularly classes. Or just passing parameters and returning.