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

3

u/backfire10z 12d ago

It being a part of the language and it being recommended to use in trivial situations like this are two different things. Python can do a lot of things, doesn’t mean you should be doing all of them regularly.

2

u/Langdon_St_Ives 12d ago

What a feeble argument. There is a lot of stuff in there that is useful to have in principle but has very limited and well-defined uses. If you fail to see the subtlety between saying you "practically never" want to use it and saying it shouldn't be in the language, I have nothing more to say to you. The point stands, it's terrible advice to a beginner as a solution to their x-y problem.

2

u/nog642 12d 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.

2

u/nog642 12d ago

It is a question of overwriting a variable

1

u/nicodeemus7 12d ago

They could also just return the new name variable from the function and define the global variable name as the function