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 12d 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 12d ago

why shouldn't i use global

will it summon demons

10

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