Brief Intro to Python Variables

advertisement
Variables in Python
Python is a foreign language.
So its parts of speech and its grammar are different – we are not in Kansas anymore,
Toto!
In English you have nouns like dog, cat, Joseph, tent
And pronouns like she, him, it, they.
Instead of nouns and pronouns, Python has variables.
A variable is like a pronoun because it can refer to different things at different times.
However, there are an unlimited number of variables – any word spelled with just letters
and digits makes a variable. Examples are;
She, him, it, they, r2d2, sum, pointOfSale,
rabbit, xyz, nonono, id3459BK
Another difference from English is that capital
letters matter.
The variables She and she are considered different – even if the She appears at the
front of the sentence.
Python does NOT capitalize the first word of every sentence. For example:
she.hit(Billy)
does NOT capitalize the she.
Nor do Python variables have cases. In English, she and her have the same meaning –
just different cases. In Python she and her are completely different variables.
In addition to being used as pronouns, Python variables are also used as nouns – both
proper nouns such as John and generic nouns such as cat, dog, person, building, tank,
lake.
When a Python variable is used as a noun, the programmer must be careful not to change
its reference (called its antecedent in English class).
In English you might say:
John gave Mary a kiss. Then he rode off into the sunset.
And the reader has to figure out that the he refers to John. The assignment of an
antecedent to the pronoun is implied.
In Python, the reference for a variable (i.e. pronoun) has to be made explicitly – for
example like this:
variable = reference
which is called an assignment command.
In Python the above English might become:
he = John
he.gaveKiss(Mary)
he.rodeoff(where=sunset)
The Python equivalent of verbs, objects, and prepositional phrases will be discussed later.
Pay close attention while you try these commands in a Python Shell:
sum =
print
sum =
print
sum =
print
45
sum
82
sum
sum+100
sum
The command sum = sum+100 is particularly interesting. Its full English translation
is rather messy:
Find the total of the reference of “sum” and the number 100 and make “sum” now
refer to this new value – i.e. the total
Another translation is:
Make sum refer to the total of sum and 100
A better translation is:
Add 100 to sum.
Download