Your shopping cart is empty!
Using just literal constants can soon become boring - we need some way of storing any information and manipulate them as well. This is where variables come into the picture. Variables are exactly what the name implies - their value can vary, i.e., you can store anything using a variable. Variables are just parts of your computer's memory where you store some information. Unlike literal constants, you need some method of accessing these variables and hence you give them names.
Variables are examples of identifiers. Identifiers are names given to identify something. There are some rules you have to follow for naming identifiers:
Variables can hold values of different types called data types. The basic types are numbers and strings, which we have already discussed. In later chapters, we will see how to create our own types using classes.
Remember, Python refers to anything used in a program as an object. This is meant in the generic sense. Instead of saying 'the something', we say 'the object'.
We will now see how to use variables along with literal constants. Save the following example and run the program.
# Filename : var.py
i = 5
i = i + 1
s = '''This is a multi-line string.
This is the second line.'''
$ python var.py
This is a multi-line string.
This is the second line.
How It Works:
Here's how this program works. First, we assign the literal constant value 5 to the variable i using the assignment operator (=). This line is called a statement because it states that something should be done and in this case, we connect the variable name i to the value 5. Next, we print the value of i using the print function which, unsurprisingly, just prints the value of the variable to the screen.
Then we add 1 to the value stored in i and store it back. We then print it and expectedly, we get the value 6.
Similarly, we assign the literal string to the variable s and then print it.