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

29 comments sorted by

10

u/JackandFred 3h 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?

6

u/9j810HQO7Jj9ns1ju2 3h ago

why shouldn't i use global

will it summon demons

5

u/thisisappropriate 3h ago

More like time travel versions of yourself. You put in global, then you do some more things, your file becomes long or you split it up across a few files because you're doing a lot now.

name = "Alice"
something = True

def another_func():
  global name
  if something:
    name = "Carl"

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

def something_else():
  something = False
  return

def another_one():
  return

def more():
  something_else()
  another_func()
  global something
  something = False
  return

func()

How easy is this to debug? Are you following it? What if func was called "get user name" and it gets the name from an API but then it calls another function that does something else?

This is part of something called side effects which you should generally avoid in functions because it makes it harder to manage them and to track what's happening where (like "get name" should only get the name, not also set it, or "take payment" should avoid also handling calculating tax).

Its easier to debug

def get_name():
  return "Bob"

def get_address(name):
  return input(f'Hello {name}, what is your address?')

...

name = get_name()
age = get_age(name)
address = get_address(name)

because you can put a debugger on it and a breakpoint on the last line and see the output of each function assigned to the variables.

3

u/JackandFred 3h ago

Yup evil demons no less.

It’s very rare for a variable to only show up once and never again. If it did you wouldn’t need to store the value in a variable. So having it changed globally means it will be changing the variable in all places at once, regardless of how it’s being used in different places at different times. It’s a common new programmer pattern that very often causes errors. Much better to have a well defined scope of how when and where you want a variable used.

3

u/illumas 3h ago

No. Just bugs.

1

u/Langdon_St_Ives 1h ago

Let's not split hairs. This time of year, demons captures it pretty well. 🎃

1

u/AUTeach 1h ago

It's hard to understand what changed them.

The best practice is to do something like name=func('bob') and have func return the variable. That way you know when it was changed and how

1

u/TheRNGuy 2h ago

Bad coding style. 

8

u/Candid_Zebra1297 4h 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 3h ago

It is possible to make functions change variables outside of themselves.

7

u/Revolutionary-Camp69 3h ago

Possible, yes. Recommended, no.

0

u/nog642 3h ago

Yeah. But that's not what they said.

8

u/JanEric1 3h ago

because if you tell the beginner here about this then they will form bad habits. best to tell them the recommended way.

•

u/nog642 52m ago

I think it's best not to decieve. You can tell them the recommended way without lying.

1

u/Boybay_Garid 1h ago

the 'outside world' framing is actually a really solid way to think about function scope

1

u/FreeLogicGate 2h ago

Can't tell if this is a genuine question or a prank.

1

u/9j810HQO7Jj9ns1ju2 2h ago

genuine question

1

u/FreeLogicGate 2h 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

3

u/JamzTyson 3h 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 bob

or more realistically:

name = "Bob"

1

u/WorriedTumbleweed289 1h 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.

0

u/AlexMTBDude 4h 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"

12

u/Langdon_St_Ives 3h 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.

-4

u/AlexMTBDude 3h 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 3h 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.

3

u/nog642 3h 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/Langdon_St_Ives 3h 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 3h ago

It is a question of overwriting a variable

1

u/nicodeemus7 4h ago

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

0

u/nog642 3h 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.