Here's an example of what I mean:
def foo():
foo = 5
print(foo + 5)
foo()
# => 10
The code doesn't produce any errors and runs perfectly. This contradicts the idea that variables and functions shouldn't have the same name unless you overwrite them. Why does it work? And when applied to real code, should I use different function/local variable names, or is this perfectly fine?
foo = 5
creates a local variable inside your function. def foo
creates a global variable. That's why they can both have the same name.
If you refer to foo
inside your foo()
function, you're referring to the local variable. If you refer to foo
outside that function, you're referring to the global variable.
Since it evidently causes confusion for people trying to follow the code, you probably shouldn't do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With