[Tutor] Variables and constants [was Re: working with strings in python3]

Steven D'Aprano steve at pearwood.info
Tue Apr 19 20:24:03 CEST 2011


Rance Hall wrote:

> Variables are variable, that's why we call them variable.
> Constants are constant, and that's why we call them constant.

And Python has neither variables nor constants in the sense that (say) 
Pascal, C or Fortran have, even though we often use the same words.

The differences are quite deep, but they're also subtle.

In classic programming languages with variables and/or constants, the 
model is that names like "x" refer to *memory locations*. If the name is 
a variable, the compiler will allow you to mutate the value stored at 
that memory location; if the name is a constant, it won't. But once a 
name "x" is associated with memory location (say) 123456, it can never 
move. But note that the "variability" or "constantness" is associated 
with the *name* (the memory location), not the value.

In languages like Python, names are associated with values, without 
reference to memory locations. In this case, the "variability" or 
"constantness" is associated with the *value*, not the name.

Consider x = 42; x = x+1. In Pascal, C or Fortran, this will actually 
change a block of memory that had the value 42 into 43 instead:

The name x points to a memory location with value 42.
Leave the name pointing to the same place, but change the value to 43 
instead.

In Python, the situation is different:

The name x points to an object with value 42.
Leave the object 42 alone, but change the name x to point to an object 
with value 43 instead.



-- 
Steven


More information about the Tutor mailing list