r/learnpython • • Oct 26 '26

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

9

u/Candid_Zebra1297 Oct 26 '26

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 Oct 26 '26

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

7

u/Revolutionary-Camp69 Oct 26 '26

Possible, yes. Recommended, no.

-2

u/nog642 Oct 26 '26

Yeah. But that's not what they said.

8

u/JanEric1 Oct 26 '26

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

-1

u/nog642 Oct 26 '26

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

2

u/Boybay_Garid Oct 26 '26

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

1

u/After_Computer1652 Oct 27 '26

Agreed look up variable scope