It's very easy in python to create variables. They are created on assignment. Variables don't have an inherent type.


In [2]:
x = 10
y = "hello"

In reality, everything in python is actually an object. To convince yourself that this is true, try these:


In [ ]:
dir(x)
dir(y)

All the items you see on the screen belong to the respective objects. The assignment operator (=) just copies a reference to an object. e.g. when you do the following, then you don't actually copy the object - only it's reference.


In [7]:
z = x
x is z


Out[7]:
True

The "is" operator above compares two objects, and returns True(boolean) if they are actually the same object. Try the following


In [8]:
x += 5
x is z


Out[8]:
False

z is now no longer the same object as x. This happened as x itself changed into a new object. Elementary data types in python are "mutable" -- meaning that the value of the object itself can change. When any operation is applied on the object, the result is a new object. Note that the value of z itself remains unchanged due to the change to x.


In [9]:
print z


10

You are free to assign any value to any variable at any time. The following works just fine. In practise however, doing so might make it difficult for you to debug your program.


In [10]:
x = 10
print type(x)
x = "hello"
print type(x)
x = 5
print type(x)
x = 20.0
print type(x)


<type 'int'>
<type 'str'>
<type 'int'>
<type 'float'>

How do you swap two numbers without using a third variable? In python, this is simple !


In [2]:
x = 10
y = 20
print x, y
x, y = y,x # Swap!
print x, y


10 20
20 10

You can use "del" to delete a variable, and blow it out of existence!


In [4]:
x= 10
del x
print x


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/home/shkumar/python-workshop/<ipython-input-4-1915399c9a18> in <module>()
      1 x= 10
      2 del x
----> 3 print x

NameError: name 'x' is not defined