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.