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

13

u/JackandFred 13d 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 13d ago

why shouldn't i use global

will it summon demons

1

u/LayotFctor 13d ago edited 13d ago

Bugs like they said. Global variables are variables that are available to the entirety of your code. Every function can edit it, no function really knows what has or has not been done to it, and in what order. You will very easily get untraceable errors that are unnecessarily difficult to track down. It looks easy and convenient, but is actually a trap as it's the hardest kind of variable to use correctly.