Expressions, Operators, and Statements

Time for a little more lingo. All programs will contain a combination of expressions, operators, and statements.


Most programs that you write will contain expressions. An expression is a combination of values, variables, and operators. A simple example of an expression is 2 + 3.  When you type an expression at the prompt, the interpreter evaluates it, which means that it finds the value of the expression. In this case, the expression 2 + 3 evaluates to 5 (because 2 + 3 = 5).

However, a value all by itself is also considered an expression, and so is a variable, so the following are all legal expressions:

Expression Result Notes
42 42
n 17
n + 25 42

In this example, n has the value 17 and n + 25 has the value 42 because 17 + 25 = 42.


Operators are functionality that do something and can be represented by symbols such as + or by special keywords. Operators require some data to operate on and such data is called operands. In this case, 2 and 3 are the operands.

The following are expressions which contain an operator:

Expression Result Notes
2 + 3 5

We are performing addition in this example. The operator is the plus sign.

3 * 5 15

We are performing multiplication in this example. The operator is the multiplication sign.


A statement is a unit of code that has an effect, like creating a variable or displaying a value.  Statements contain expressions. Expressions may contain one or more operators.

n = 17print(n)

The first line is an assignment statement that gives a value to n. The second line is a print statement that displays the value of n.

When you type a statement, the interpreter executes it, which means that it does whatever the statement says. In general, statements don't have values – they perform actions.

Mathematical Operators

Here is a brief run through of the most common mathematical operators in Python. A special thing to note is that these operators can work on all data types – not just integers and floats. Strings, sequences, and objects can all use these mathematical operators.

+ (plus)

The plus + operator performs addition on two objects.

Expression Result Notes
3 + 5 8

Notice that the result is an integer.

1.5 + 2.5 4.0

Notice that the result is a float.

1 + 1.0 2.0

Notice that we are adding an integer and a float. The result is a float.

'a' + 'b' 'ab'

– (minus)

The minus – operator gives the subtraction of one number from the other; if the first operand is absent it is assumed to be zero. Minus does not work with strings.

Expression Result
-5.2 -5.2
50 – 24 26

* (multiply)

The multiply operator gives the multiplication of the two numbers or returns the string repeated that many times.

Expression Result
2 * 3 6
'la' * 3 'lalala'

** (power)

The power operator performs an exponentiation; that is, it returns x to the power of y. Power does not work with strings.

Expression Result Notes
3 ** 4 81

This is the same as 34 which is the same as 3 * 3 * 3 * 3

4 ** 2 16

This is the same as 42 which is the same as 4 * 4 = 16

/ (divide)

The division / operator divides x by y. Python will always return a float. Divide does not work with strings.

Expression Result Notes
13 / 3 4.333333333333333

Note that this returns a float

4 / 2 2.0

Note that even though 4 / 2 = 2, python returns a float and not an integer.

0 / 5 0.0

Note that even though 0 / 5 = 0, python returns a float and not an integer.

// (divide and floor)

The floor division operator, //, divides two numbers and rounds down to an integer. Divide and floor does not work with strings.

Expression Result Notes
13 // 3 4

Note that this returns an integer

4 // 2 2

Note that this returns an integer

0 // 5 0

Note that this returns an integer

-13 // 5 -3

Note that this returns an integer

When would you want to use this? Suppose the run time of a movie is 105 minutes. You might want to know how long that is in hours. Conventional division returns a floating-point number:

Code Output
minutes = 105 none
minutes = minutes / 60 none
print(minutes) 1.75

But we don't normally write hours with decimal points. Floor division returns the integer number of hours, dropping the fraction part:

Code Output
minutes = 105 none
hours = minutes // 60 none
print(hours) 1

To get the remainder, you could subtract off one hour in minutes:

Code Output
remainder = minutes – hours * 60 none
print(remainder) 45

% (modulo)

The modulus operator % divides two numbers and returns the remainder.

Expression Result Notes
13 % 3 1

Note that this returns an integer

-25.5 % 2.25 1.5

Note that this returns a float

We can use the modulus operator % on our movie running time example.

Code Output
remainder = minutes % 60 none
print(remainder) 45

The modulus operator is more useful than it seems. For example, you can check whether one number is divisible by another – if x % y is zero, then x is divisible by y.

Also, you can extract the right-most digit or digits from a number. For example, x % 10 yields the right-most digit of x (in base 10). Similarly x % 100 yields the last two digits.

Assignment and Operation Shortcuts

It is common to run a math operation on a variable and then assign the result of the operation back to the variable, hence there is a shortcut for such expressions:

a = 2a = a * 3

can be written as:

a = 2a *= 3

Notice that variable = variable operation expression becomes variable operation= expression.

Other examples:

Long Code Shortcut Code
a = a + 5 a += 5
a = a – 2.25 a -= 2.25
a = a * 4 a *= 4
a = a/3 a /= 3

Order of Operations

If you had an expression such as 2 + 3 * 4, is the addition done first or the multiplication?

When an expression contains more than one operator, the order of evaluation depends on the order of operations. For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules:

  • Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even if it doesn't change the result.
  • Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2 * 3**2 is 18, not 36.
  • Multiplication and Division have higher precedence than Addition and Subtraction. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
  • Operators with the same precedence are evaluated from left to right (except exponentiation). So in the expression degrees / 2 * pi, the division happens first and the result is multiplied by pi. To divide by 2 π, you can use parentheses or write degrees / 2 / pi.

I don't work very hard to remember the precedence of operators. If I can't tell by looking at the expression, I use parentheses to make it obvious.

For example, 2 + (3 * 4) is definitely easier to understand than 2 + 3 * 4 which requires knowledge of the operator precedences. As with everything else, the parentheses should be used reasonably (do not overdo it) and should not be redundant, as in (2 + (3 * 4)).

There is an additional advantage to using parentheses – it helps us to change the order of evaluation. For example, if you want addition to be evaluated before multiplication in an expression, then you can write something like (2 + 3) * 4.

Operators are usually associated from left to right. This means that operators with the same precedence are evaluated in a left to right manner. For example, 2 + 3 + 4 is evaluated as (2 + 3) + 4.

Example: Calculating on a Rectangle

Type and run the following program:

length = 5breadth = 2area = length * breadthprint('Area is', area)print('Perimeter is', 2 * (length + breadth))


Area is 10Perimeter is 14

How It Works

Here's how this program works.

Code Output Notes
length = 5 none

First, we assign the literal constant value 5 to the variable length using the assignment operator (=).

breadth = 2 none

Next, we assign the literal constant value 2 to the variable breadth using the assignment operator (=).

area = length * breadth none

We use these to calculate the area and perimeter of the rectangle with the help of expressions. We store the result of the expression length * breadth in the variable area

print('Area is', area) Area is 10

Next, we print the value of area using the print statement.

print('Perimeter is', 2 * (length + breadth)) Perimeter is 14

Finally, we directly use the value of the expression 2 * (length + breadth) in the print function to display the perimeter of the rectangle.

Notice how Python pretty-prints the output. Even though we have not specified a space between 'Area is' and the variable area, Python puts it for us so that we get a clean nice output and the program is much more readable this way (since we don't need to worry about spacing in the strings we use for output). This is an example of how Python makes life easy for the programmer.

Getting Input from the Keyboard

There will be situations where your program has to interact with the user. For example, you would want to take information from the user and then display some results back. We can achieve this using the input() function and print function respectively.

The built-in function, input, stops the program and waits for the user to type something. When the user presses Return or Enter, the program resumes and input returns what the user typed as a string.

Look at the following example:

my_name = input('What is your name?')print(my_name)

When we execute this code, the interpreter will prompt us for our name and allow us to enter whatever we like.

code example

Code Output Notes
my_name = input('What is your name?') What is your name?

When this code is executed, the program displays the input statement's prompt string, in this case What is your name? and waits for the user to provide some input. The program pauses until the Enter or Return key is pressed. Then the program assigns the input received from the user – in this case the string Heather –  to the variable my_name and continues.

print('Hi,', my_name) Heather

Now that the program has received input from the user, we display the string Hi, followed by the value of my_name – Heather – using the print statement.

Notice that the input received from the user – in this case the string Heather – is right up against the prompt What is your name? This is rather ugly. You can make it look nice by either adding a space at the end of the prompt:

Or you can cause the input to be entered on a new line by using a special sequence n. As you should recall, the sequence n at the end of the prompt represents a newline and causes a line break.

Converting Input to Integers and Floats

Also notice that everything which is entered by the user has a type of string. Even numbers. If you need to use the user's input to perform a mathematical calculation, you will need to convert the string to either an integer or to a float before you perform the calculation. To do this, you use the statements int() and float().

Code Output Notes
my_age = input('What is your age?')my_age = int(my_age) none

Get the user's age. It is automatically a string, even if the user types a number.

Convert the the my_age variable to an integer using int().

Now you can perform mathematical calculations on the number.

cost = input('Enter the cost')cost = float(cost) none

Get the cost of an item. It is automatically a string, even if the user types a number.

Convert the the cost variable to a float using float().

Now you can perform mathematical calculations on the number.

However if the user types something other than a valid number, you will get an error if you use int() or float().

>>> age = input('How old are you?')How old are you?too old>>> int(age)ValueError: invalid literal for int() with base 10

We will see how to handle this kind of error later. But this is something to keep in mind – users will unintentionally mess up your programs and it is important to plan for it.

Converting Integers and Floats to Strings

There may come a time when you need to convert an integer or float to a string. To do this, you use the str() statement:.

Code Output Notes
my_age = 20my_age = str(my_age)print(type(my_age))

Assign the integer 20 to the variable my_age.

Convert the the my_age variable to a string using str().

cost = 19.25cost = str(cost)print(type(cost)) none

Assign the float 19.25 to the variable cost.

Convert the the cost variable to a string using str().

Debugging, Part 2

Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic errors. It is useful to distinguish between them in order to track them down more quickly.

Syntax error:

"Syntax" refers to the structure of a program and the rules about that structure. For example, parentheses have to come in matching pairs, so (1 + 2) is legal, but 8) is a syntax error.

If there is a syntax error anywhere in your program, Python displays an error message and quits, and you will not be able to run the program. During the first few weeks of your programming career, you might spend a lot of time tracking down syntax errors. As you gain experience, you will make fewer errors and find them faster.

Runtime error:

The second type of error is a runtime error, so called because the error does not appear until after the program has started running. These errors are also called exceptions because they usually indicate that something exceptional (and bad) has happened.

In the previous section, you saw that a ValueError was thrown when we tried to convert the string old to an integer. This is an example of a runtime error.

Semantic error:

The third type of error is "semantic", which means related to meaning. If there is a semantic error in your program, it will run without generating error messages, but it will not do the right thing. It will do something else. Specifically, it will do what you told it to do.

Identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing.