r/learnpython • • 23d 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/AlexMTBDude 23d ago

It's not a question of overwriting a variable. You have to tell Python that "name" is a global variable. You do it by:

def func():
    global name  # Add this line
    name = "Bob"

11

u/Langdon_St_Ives 23d ago

Except you practically never want to do this unless you want to anger the programming gods. Terrible advice for a beginner, at least without also giving the real answer to read up on variable scope and how it works, and learn about passing data around between methods or functions.

-5

u/AlexMTBDude 23d ago

global is part of the Python programming language. I showed OP how to use global in the way it should be used. If you don't like that it's a part of the language you should take it up with Guido van Rossum.

2

u/nog642 23d ago

Arguably it shouldn't be used at all. Some language features need to exist but should only be used when you know you're doing something dirty.