Informatics Practices · Ch 3 — Brief Overview of Python
Variables
Variables
A variable is an identifier whose value can change during the life of a program. The name stays fixed; what it refers to may vary. A variable called age, for instance, can hold a different value for each person it describes — the same name, reused for changing data. This ability to attach a name to a value, and to change that value later, is what makes programs flexible instead of being one-off calculations.
Two basic facts about variables:
- A variable name must be unique within a program. One name refers to one thing at a time; you cannot have two different variables both called
agein the same program. - The value a variable holds can be of different kinds — a string (such as 'b' or 'Global Citizen'), a number (such as 10, 71 or 80.52), or any combination of alphanumeric characters, that is, a mix of alphabets and numbers such as 'b10'.
In Python, a variable comes into existence through an assignment statement: writing the name, the equals sign, and the value creates the variable and stores that specific value in it.
gender = 'M'
message = "Keep Smiling"
price = 987.9
Each of these lines creates a new variable and assigns it a value — a single character string, a longer string, and a decimal number respectively.
Two rules of behaviour follow from how the interpreter treats variables:
- A variable must always be assigned a value before it is used anywhere in the program. Using a name that has never been assigned leads to an error — there is simply no value for the interpreter to work with.
- Wherever a variable name occurs in the program, the interpreter replaces it with the value of that variable at that moment. When you write
num1 + num2, the interpreter substitutes the stored values and adds those.
This substitution idea is exactly what the two worked programs demonstrate.
Program 3-2: a Python program to find the sum of two numbers.
#Program 3-2
#To find the sum of two given numbers
num1 = 10
num2 = 20
result = num1 + num2
print(result) #print function in python displays the output
Output:
30
Read it as the interpreter does. The first two assignments create num1 holding 10 and num2 holding 20. In the third line, each name is replaced by its value, so num1 + num2 becomes 10 + 20, and the result, 30, is stored in a third variable named result. Finally print(result) displays the output — print() is the Python function that shows a value on the screen. Notice also the lines beginning with #: these are comments, remarks for the human reader that the interpreter ignores.
Program 3-3: a Python program to find the area of a rectangle whose length is 10 units and breadth is 20 units.
#Program 3-3
#To find the area of a rectangle
length = 10
breadth = 20
area = length * breadth
print(area)
Output:
200
``` …