Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it wrong to use same names for variables inside the function definition as thevariables used when calling a function in python

Tags:

python

basically what the title says.

say i got a function definition

def add_one (num1):
    numOut = num1 +1
    return numOut

and im calling the function as follows

num1 = 11
numOut = add_one (num1)

is this considered bad practice, as we are naming two different objects with the same name, or is it good practice s it increases readability? Or is it something that I am missing completely?

(also checked pass variable to function using same name and Is it normal to use in the function some variable with the same name as it function? but they do not refer to python)

like image 441
elfe Avatar asked Jan 26 '26 07:01

elfe


1 Answers

First, lets talk about scopes:

In python and a lot of other languages variables exist within its scope. This means that if you create a variable inside a scope it will stop existing when you leave that scope.

Variables on a outer scope are also accesible within an inner scope but if you asing something to that variable then it will be redeclared as a local variable inside this scope. Meaning that that variable will be diferent than the one on the outer scope.

If you ask me, I don't think is a bad practice to use the same name as the arguments of your functions. In fact I would call bad practice trying to avoid that as you would end up tryining to figure out new names for different variables that have the same meaning.

What you should avoid is to use variables that are not on the local scope (no matter what language are you using).

like image 167
Òscar Raya Avatar answered Jan 27 '26 19:01

Òscar Raya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!