[Tutor] Functions and Variable Names

Jeff Shannon jeff@ccvcorp.com
Mon Feb 24 18:48:01 2003


bob smith wrote:

 > I'm back with another question about functions and variable names.
 >
 > Okay, if I have separate functions, I know I can pass a value between
 > them with the same variable name.  But is that considered poor
 > programming?  Will it make things unclear? [...]
 >
 > "score" is the prefect name for what I'm representing, but should I
 > have different names for this value in each function?  This would seem
 > odd to me, but I'm trying to learn the best way to program in Python.


This is perfectly reasonable.  A variable should be given a name which
makes the most sense *in that context* -- that is, within the 
function, class, or module that it's part of.  If several different 
functions end up using a variable with the same name, well, that's 
okay.  The trick is that it's important to keep in mind that, even 
though the name is the same, they are *different variables* -- the 
'score' in f2() is different from the 'score' in main(), even though 
they have the same name and the same value.  You can make a change to 
'score' within f2() and that won't affect the 'score' that's in 
main().  (This can be complicated by the fact that sometimes, 
different variables can refer to the same object, but that's a 
different question. ;) )

Jeff Shannon
Technician/Programmer
Credit International