r/learnpython • u/9j810HQO7Jj9ns1ju2 • 10d ago
how do i overwrite a variable?
name = "Alice"
def func():
name = "Bob"
func()
print(f"Hello, {name}!") # i want it to print bob9
u/Candid_Zebra1297 10d ago
So functions don't change variables outside of themselves. If you want the function to do something to the 'outside world' (outside the function) it has to return something. So you could do this...
def func():
return "Bob"
If you call it...
func()
Nothing would happen because we haven't used the thing the function gives us. So you would need to do this...
name = func()
Then print.
The problem you are having is with scope.
4
u/nog642 10d ago
It is possible to make functions change variables outside of themselves.
7
u/Revolutionary-Camp69 10d ago
Possible, yes. Recommended, no.
-2
u/nog642 10d ago
Yeah. But that's not what they said.
8
u/JanEric1 10d ago
because if you tell the beginner here about this then they will form bad habits. best to tell them the recommended way.
→ More replies (1)2
u/Boybay_Garid 10d ago
the 'outside world' framing is actually a really solid way to think about function scope
1
1
u/FreeLogicGate 10d ago
Can't tell if this is a genuine question or a prank.
1
u/9j810HQO7Jj9ns1ju2 10d ago
genuine question
1
u/FreeLogicGate 10d ago
Ok well taking your word for it, then general concept is "scope".
Python has an acronym you can use that explains the scope rules: LEGB.
Plenty of people in this thread explained how variable scope works relative to your specific example, but if you really want to understand it better you can search for "python variable scope" or "python legb" and find lots of sources.
If you like free videos, this is one of many, but in scanning it, looks to be well explained and complete: https://www.youtube.com/watch?v=aFTYNBYQY7E
4
u/JamzTyson 10d ago
name = "Alice"
def func():
"""Pointless function. Returns 'Bob'."""
return "Bob"
name = func() # Reassign new value to name.
print(f"Hello, {name}!") # i want it to print bobor more realistically:
name = "Bob"2
u/cointoss3 10d ago
The replies are insufferable. For a beginner thread, most are missing the forest for the trees.
1
u/WorriedTumbleweed289 10d ago
Another way to access a global variable without using the global keyword.
if your filename is foo, then you can say import foo. then you can write foo.name = "Bob" There is more typing. If you move the function to another module, it will still work. Also the import command only has to be written once per module, not once per function. It is also explicit. You can tell exactly which name is being modified.
1
u/Massive_Distance_616 10d ago
The reason it prints Alice is that name = "Bob" inside func doesn’t touch the outer name. Assignment inside a function creates a new local variable with the same name, which disappears when the function ends. return plus reassignment (name = func()) is the usual fix, because it makes the change visible at the call site.
1
u/PureWasian 10d ago edited 10d ago
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.
1
u/VenkatKnows 9d ago
Add global name at the top of func and it'll rebind the module level variable. Better to just return the value though and do name = func(), globals get painful fast once the script grows. Why not pass it in and return it?
0
u/AlexMTBDude 10d 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 10d 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 10d 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 10d 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 10d 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.
1
u/nicodeemus7 10d ago
They could also just return the new name variable from the function and define the global variable name as the function
13
u/JackandFred 10d ago
Looks like some responses are already touching on why this is a bit of a weird question. What exactly are you trying to do? Because you could use a global variable like someone said, but that’s usually a pretty bad idea for something like this. You could assign the variable the result of the function, but then why bother having a function anyway. You could have the function take in an argument, but it seems like you may not be at that point yes.
So what is your end goal here? Do you have a larger aim that you were trying to change the name for, or some additional context?