Variables, Operators and Expressions

Table of contents:

Python Variables, Operators and Expressions

Variable is the most important term in the world of programming. All programming languages use variables. Before we go through the term "varable", let us find what are objects in python.

Table of contents:

Python Variables

A python variable is a name that points to a particular python object; or, it is a label attached to an object in the memory. Every variable has a valid name. To create a variable, we give it a name, and assign a value or literal to it.

Later we use this value by including the name of the variable in expressions, functions, assignments etc.

There are rules to be obeyed while naming a variable. In python, a variable-name may contain any alphabet, lowercase or uppercase, any digit from 0 to 9, and the underscore(_).

A variable-name must begin with an alphabet or an underscore(_). But preferably, always use alphabets in the beginning.

A variable-name should not be a python reserved word like if, else, for, def etc.

Following are invalid as a variable name:

Invalid nameReasonPossible valid name
defpython reserved worddef11
is-red-colorinvalid character hiphenis_red_color
1datefirst character is a digitdate1

Python raises an SyntaxError when it finds an invalid variable name.

We create variables and assign literals to them with assignment statements as follows:

The = is an assignment operator. To the left of it sits the variable; its name is chosen by the programmer. To the right of the operator we put a literal, or expression.

When the assignment statement x = 1 is executed, an integer object 1 is created, and then a label named x points to this object 1. In another word, we say that 1 is assigned to x, or x holds the value 1.

>>> >>> | Press ENTER here variable assignment operator integer literal (assigned value)

The data-type of an object becomes the data-type of the associated variable. In the above,
x is an integer variable (∵ it points to an integer object).
radius is a float variable (∵ it points to a float object).
country is a string variable (∵ it points to a string object).

That the variable x holds the value 1, we can check this with a print() function.

The value of the variable x is displayed in the third line. Without executing the x = 1 statement, the print(x) would have resulted in a NameError, because x would have been undefined then.

Let us reassign a new value 25 to x and use the print() again.

The current value of x is displayed as 25.
More specifically, another integer object 25 is created, and x now points to that new object.

This is why we call x a variable, it's value can vary at different points of time.

We decided both the name x, and the value 1. Python just created them as per the instructions. The life of this variable ends when we close the IDLE window or python shell.

Two variables lan and wan are created and two string literals are assigned to them. Then the values are displayed.

Only the current value of a variable is used. In the above, when we execute print(js), its current value was "javascript".

Operators and operands

An operator is a special symbol that represents a particular action. For example, an addition operator + indicates that two operands on the both sides of the operator are to be added.

The term 99 + 1 indicates an addition operation between 99 and 1, the + symbol being the operator, and 99 and 1 being the operands.

In the above, 99 and 1 are operands, and + is the operator.

An operand is the target of a mathematical operation, as seen in the above. Operators are applied on operands to evaluate an expression.

Operators operating on two operands are called binary operators. For example, the following operators take two operands.

+, -, *, /, //, %, **, ==, !=, <, <=, >, >=, and, or, &, |, ^, <<, >>, is, is not, in, not in and :=

Operators operating on a single operand are called unary operators. For example, the following operators take a single operand.

+x (unary positive), -x (unary negation), ~x (bitwise negation) and not

A full list of python arithmatic, comparison, logical, identity, membership operators can be found in operator precedence page.

What are expressions

Basically, expressions are a combination of operands and operators.
They may contain at least one operand(or more), zero or more operators, and zero or more pairs of parentheses.

An expression can always be evaluated to a single value.

During the study of earlier pages, we have found many expressions containing python objects like integers, floats, strings, variables, constants, lists, functions, operators etc.

Following are valid python expressions.

The expression celsius * 9 / 5 + 32 contains four operands(one variable included) and three operators.

celsius * 9 / 5 + 32 variable operators operands

Even single values like 11, 24, "Hello World!" are also valid expressions.

In python, the following are valid expressions:

Following another three valid expressions with explanations:

my_string == "Hello World!"
Contains: 1 comparison operator (==)
Contains: 2 operands,
1 variable(my_string), 1 string literal("Hello World!")
Output data-type is 'bool', True or False

a ** 2 + 2 * a * b + b ** 2
Contains: 6 operators, arithmetic(**, +, *, *, +, **)
Contains: 7 operands,
4 variables(a, a, b, b), 3 numeric literals(2, 2, 2)
Output data-type is 'int' or 'float'

x + 3 > y + 2 and z != 9
Contains: 5 operators,
2 arithmetic(+, +), 2 comparison(>, !=), 1 logical(and)
Contains: 6 operands,
3 variables(x, y, z), 3 numeric literals(3, 2, 9)
Output data-type is 'bool', True or False

Every expression in the above evaluates to a single value.

Generally expressions are evaluated from left to right, but operator precedence is taken into account.

This is because the * operator has higher precedence over the - operator. So, 5 * 2 is evaluated first, then 4 - 10 is evaluated.

Using variables in arithmetic operations

In the previous page, we have seen how to add two numbers. We can also perform arithmetic operations with variables. We declare two variables with two different values.

In the first two statements, the literal 13 is assigned to x, and 11 is assigned to y.

The third statement in the above is the most important.

Here, the right hand side expression is taken first; x and y are substituted by their current values. So the expression x + y becomes 13 + 11.

Because of the addtion operator + inbetween, the expression is evaluated to 24. This result 24 is assigned to the variable my_var.

All of those are done with the single statement my_var = x + y.

my_var holds the sum of x and y. Now if we change the value of variable y,

that does not change the value of my_var. But y changes to 20.

In the above, the expression x - y, after variable substitution, becomes 13 - 20 and then evaluates to -7.
x * y becomes 13 * 20, and evaluates to 260. The operator * performs multiplication between two operands.

Let us check the data-type of the variable my_var at this point.

Data-type of my_var is 'int', as it holds the integer object 260.

The expression x / y after variable substitution becomes 13 / 20 and evaluates to 0.65.

The / being the operator for division, performs division operation between two operands 13 and 20.

Notice that data-type of my_var has changed to 'float', since it holds the floating point object 0.65.

Using variables in mathematical formulae

The following three consecutive examples demonstrate how to use mathematical formulae with variables in python:

Two integer literals 6 and 3 are assigned to the variables base and height.

Then we assign an expression 0.5 * base * height to variable area.

When the 3rd line is executed, python takes the right hand side expression 0.5 * base * height for evaluation. The variables base and height are substituted with their respective values. Then the expression 0.5 * 6 * 3 is evaluated to 9, and the result is stored in the variable area.

The print() in line 4 produces the final result in line 5.

Here is an another example. In python, the ** stands for exponent operation.

In the above, the expression radius ** 2 is evaluated as radius2.

By substitution, the expression pi * radius ** 2 becomes 3.1415 * 4 ** 2.

3.1415 * 4 ** 2 is mathematically 3.1415 × 42, and evaluated to 50.264.

In the following, we go with another example of using variable in mathematical formula.

In the above, after substitution of the variables, the expression celsius * 9 / 5 + 32 becomes 40 * 9 / 5 + 32, and then evaluated to 104.0.
Carefully observe the last print(); it looks a bit complex, but actually contains four expressions seperated by commas.

If we change the value of the variable celsius to 30, variable fahrenheit will produce the value 86.0 and the final output will be 30 deg C = 86.0 deg F.
But to get this output, we have to re-type all the three statements, because we are using the IDLE shell here.

The script mode

Here comes the script mode handy for us.

In interactive mode like inside IDLE or python shell, one statement is entered and executed immediately, while the interpreter waits for the next statement.

In script mode, we use some text editor like Visual Studio Code or Pycharm to create a text file with .py extension, say, fahrenheit.py. We write the above three python statements in this file. With the .py extension, this file becomes an actual python program or script.

Now if we execute the program, all the three statements will be executed from top to bottom, in a single run. Following is the python script or program with its output:

After we complete writing all the required statements, we save the file and run/execute the script. 40° celcius is converted to equivalent fahrenheit value, and the output is displayed in the output window.

Now change line 2 to celsius = 30, and save again, and re-run:

Now 30° celcius is converted to equivalent fahrenheit value. The same code can be re-used for any value of celsius, the output (fahrenheit value) will change accordingly.

The statements to find the area of a triangle may be written in another file, say triangle.py as in the following:

Changing the value of base or/and height at line 2 or/and 3 will produce different values of area, the structure of the script remaining the same.

To find the area of a circle we write the script like this:

--- x ---

Want to leave a message for me?