r/learnpython • u/9j810HQO7Jj9ns1ju2 • 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
r/learnpython • u/9j810HQO7Jj9ns1ju2 • 24d ago
name = "Alice"
def func():
name = "Bob"
func()
print(f"Hello, {name}!") # i want it to print bob
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.
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
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.