Using just literal constants can soon become boring - we need some way of storing some information and manipulate that information. This is where variables come into the picture. Variables are exactly what they mean - their value can vary i.e. you can store anything in 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 i.e. you give them names.
Variables are examples of identifiers. Identifiers are names given to identify something. There are some strict rules you have to follow for naming identifiers:
The first character of the identifier must start with a letter of the alphabet (upper or lowercase) or an underscore ('_').
The rest of the identifier name can consist of letters, underscores or digits.
Identifier names are case-sensitive. For example, myname and myName are not the same. Note the lowercase n in the former and the uppercase N in the latter.
Examples of valid identifier names are i, __my_name, name_23, and a1b2_c3.
Examples of invalid identifier names are 2things, this is spaced out and my-name.
Variables can hold values of different types called data types. The basic types are numbers and strings, which we have already discussed. We will see how to create your own types using classes in the chapter on object-oriented programming.
Remember, Python refers to anything used in a program as an object. This is meant in the generic sense. Instead of saying "the something that we have", we say "the object that we have" .
Python is strongly object-oriented in the sense that everything is an object including numbers, strings and even functions.
We will now see how to use variables along with literal constants. Save the following example and run the program.
Henceforth, the standard procedure to save and run your Python program is as follows.
Open your favorite editor.
Enter the program code given in the example.
Save it as a file with the filename mentioned in the comment. All Python programs should have an extension of .py .
Run the interpreter with the command python program.py or use IDLE to run the programs. You can also use the executable method as explained earlier.
Example 4.1. Using Variables and Literal Constants
#!/usr/bin/python # Filename : var.py i = 5 print i i = i + 1 print i s = '''This is a multi-line string. This is the second line.''' print s
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. Next, we print the value of i using the print statement.
Then, we add 1 to the value stored in i and store it back in i and then we print the value to confirm that it is indeed 6.
Similarly we assign the literal string to the variable s and then print it.
Variables are used by just naming them and assigning a value. No declaration or data type definition is required.