The story of variables

Let’s give some rest to Neko and look at something else
in this chapter!

Type the following at the Python prompt:

a = 1

What have you done? Programmer’s would tell you that
you have just now created a `variable’ and `assigned’
a value of 1 to it!

But we know better! Look at the figure below:

That’s it! We have created a name tag called “a”
and we have hung it over 1! Now, whenever we say “a”
in our program, it stands for 1. Check it out by simply
typing “a” at the Python prompt and hitting the “enter” key.
This is what you will see:

>>> a
1
>>>

What if we type:

a = 2

Again, the figure below gives us the answer:


The label now hangs over the neck of 2!

What if we do:

a + 1

Simple, “a” stands for 2, so “a+1″ gives us 3!

You can stick any number of labels to a number. Thus, if
you do:

b = a

This is what happens:

What if we do:

a + b

Python gives us “4″ as the answer - which is right because
“a” stands for 2 and “b” also stands for 2. So “a+b” stands
for 4. This is what we see at the Python prompt:

>>> a + b
4
>>>

What about this:

c = a + b

You can easily imagine a label “c” hanging over the number 4!

Check this by typing c+1 at the Python prompt - you will get 5.

Here is something more tricky:

a = 2
a = a + 1

We know that becuase “a” is 2, a+1 is 3. So, writing “a = a + 1″ is
same as writing a = 3.

If we do “a=a+1″ once again, “a” will become 4 and so on …

If you wish to read out that line (a = a + 1) aloud, you
might say something like this:

New value of “a” is old value of “a” plus one

Another thing - our “name tags” (sorry, variables) can have
much better names than “a”, “b”, “x”, “y” etc. For example,
you can create variables like:

chemistry = 35
maths = 46
physics = 48
total = chemistry + maths + physics
length = 5
breadth = 4
area = length * breadth

What are you waiting for - go on and try out some experiments on your own!

These `name tags’ (variables) are going to be very useful
for us in the coming chapters!

One Comment

  1. Posted January 31, 2008 at 12:49 pm | Permalink

    The `name tag’ idea was stolen from the `idiomatic python’ article:

    http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html

    You should definitely read it if you are a Python programmer!

    I hope the author of the article doesn’t mind me copying the png images on his page!

Post a Comment

Your email is never published nor shared.