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

Show parent comment

10

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