I was wondering if it would be preferable to use " n " as part of the loop to call the function with n = whatever and have the function variable to be " n " also. Or do they have to be different. My textbook uses different variables. I just wanted a second opinion if one is more preferable than another.
# Math pentagonal numbers
pentagonal_number = int(n * (3 * n - 1) / 2)
count = 0
for n in range(100):
print(format(get_pentagonal_number(n), "10d"), end=' ')
count += 1
if count % 10 == 0:
Variable names are arbitrarily assigned by the author, for reasons governed by their thinking and rationale. The considerations the author is faced with are scope and mutability, derivation and purpose.
In simple functions a single letter or short name are condusive to the basic purpose they serve. This is the mundane side of code that deserves no more letters in the name than really needed.
Your question relates to what happens when we assign a value to the parameter variable, which is to overwrite the inputs. Not the most favorable approach if the input is to be treated as a constant in the function.
Ideally, working variables should have simple and practical names that do not interfere with the data inputs. Treat the inputs as sacrosanct. Don’t overwrite them. Compute what is needed and return the result. If the input must needs be changed, create a copy and change it. Preserve inputs unless you are certain they are destructible.
So in the case of a loop iterator variable, pick something simple, and typical or borrowed from convention. What if the parameter is a name of more semantic value than a letter? Within the function a simple one letter variable name is practical, since it does not bury the parameter variable in verbosity. Keep these ideas on hand and you will guide yourself through the process of variable naming in your code design.
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.