SchoolWhool
Quizzes and saved progress, freeSign in freeSign in

Python 1.6Free video15 minLesson 6 of 6 in Module 1

Operators

Compute and compare with Python's operators, and know their precedence.

Free sample. Everything in this module opens with a free account.

Watch or read the lesson: Operators

01Operators and expressions

So far you have used Python to add prices, calculate a tip and split a bill. Every one of those calculations used an operator, like + for addition and * for multiplication. Operators do more than arithmetic, though. They also let you compare values and combine conditions.

This lesson goes through the rules Python follows, so that you can look at an expression and predict what it will produce before you run it.

Start with a simple expression:

10 + 3
13

The + sign is called the operatorKey termA symbol or word that performs an operation: +, //, ==, and, in.. The values 10 and 3 are called operands. The operator tells Python which operation to perform, and the operands are the values it performs that operation on.

The whole thing, 10 + 3, is an expressionKey termAny piece of code that Python evaluates to a value: 10 + 3, price * 2, age >= 18.: a piece of code that Python evaluates to produce a value. This one evaluates to 13. You met expressions in the first-code lesson. This lesson looks at the operations inside them.

02Arithmetic operators

Python has seven basic arithmetic operators:

OperatorName
+addition
-subtraction
*multiplication
/division
//floor division
%modulo
**exponentiation

Addition, subtraction and multiplication

The first three are probably exactly what you would expect. The plus sign adds two values, the minus sign subtracts one from another, and the star multiplies them.

10 + 3
13
10 - 3
7
10 * 3
30

The same two operands, three different operations, and nothing surprising so far.

Division

For division, Python uses the forward slash, /. Dividing 10 by 3:

10 / 3
3.3333333333333335

That is approximately 3.3333, with more digits continuing after the decimal point.

Predict first

Now a question. What if you divide 10 by 5? Both numbers are integers, and the answer is exactly 2. So does Python return the integer 2, or the float 2.0? Think it through before reading on.

I have a guess. Show meHide the answer
10 / 5
2.0

You get 2.0, a float. In Python, regular division with the forward slash produces a float when you are working with integers or floats, even if the result is a whole number. So 10 / 5 gives 2.0, not 2.

Floor division and modulo

Python has a second division operator, useful when you only want whole units. It is called floor divisionKey term//: divides, then rounds down toward negative infinity. 10 // 3 is 3, and -7 // 2 is -4., and you write it with two forward slashes:

10 // 3
3

There are 3 complete groups of 3 in 10, so floor division gives 3. But that leaves something over, and that is where another operator comes in. The moduloKey term%: the remainder after floor division. 10 % 3 is 1, and -7 % 2 is 1. operator, written with the percent sign, gives the remainder of a division:

10 % 3
1

Three groups of 3 make 9, and 1 is left over.

Breaking a duration into hours, minutes and seconds

When would you actually use floor division and modulo? They are especially useful when you want to break a quantity into smaller units.

Imagine you have just finished a workout, and your fitness tracker tells you it lasted 7,384 seconds. That is not a very convenient way to show a duration. You would rather see hours, minutes and seconds. So how do you convert it?

First, find the number of complete hours. There are 3,600 seconds in an hour, so use floor division to divide 7,384 by 3,600:

seconds = 7384
hours = seconds // 3600
hours
2

That means two full hours. But there are still some seconds left over, and modulo finds them:

remaining = seconds % 3600
remaining
184

7,384 modulo 3,600 leaves 184 seconds. Now, how many complete minutes are there in 184 seconds? Use floor division again, this time by 60:

minutes = remaining // 60
minutes
3

Three minutes. Finally, modulo 60 gives the seconds that remain after those minutes:

remaining_seconds = remaining % 60
remaining_seconds
4

Put the three numbers together in an f-string:

print(f"{hours} hours, {minutes} minutes, "
      f"{remaining_seconds} seconds")
2 hours, 3 minutes, 4 seconds

So the workout lasted 2 hours, 3 minutes and 4 seconds. That is how floor division and modulo work together: floor division counts the complete units, and modulo finds what remains.

Exponentiation

There is one more arithmetic operator: exponentiation, raising a number to a power. In Python you write it with two stars. 10 ** 3 means 10 to the power of 3, which is 10 multiplied by itself three times:

10 ** 3
1000

Exponentiation is useful in all sorts of calculations, compound interest for example. Imagine you invest 1,000 dollars at an annual interest rate of 5 percent and leave it invested for 10 years. If the interest compounds once per year, each year multiplies the balance by 1 + 0.05, so after 10 years the final amount is the starting amount times (1 + 0.05) ** 10:

1000 * (1 + 0.05) ** 10
1628.894626777442

Formatted to two decimal places, the way you would show money:

print(f"{1000 * 1.05 ** 10:.2f}")
1628.89

That is approximately 1,628 dollars and 89 cents. With a few arithmetic operators you have done a calculation that would otherwise take quite a few steps.

The type of the result

Before moving on, there is something important to understand about the type of each result.

  • With addition, subtraction or multiplication on two integers, the result is normally an integer.
  • The same is true for floor division and modulo when both operands are integers.
  • Regular division with / gives a float, as you saw with 10 / 5.
  • When you mix an integer with a float in basic arithmetic, the result is generally a float.

For example:

result = 7 + 2.0
result, type(result)
(9.0, float)

7 + 2.0 gives 9.0, a float, because one of the operands is a float.

03Floor division with negative numbers

Floor division has one behavior that catches a lot of beginners off guard, especially when negative numbers are involved.

Predict first

What do you think -7 // 2 returns: -3, or -4? Think it through before reading on.

I have a guess. Show meHide the answer
-7 // 2
-4

Why -4? The answer is in the name of the operator: it is floor division. It rounds the result of the division down, toward negative infinity. That is different from simply removing the decimal part.

-7 divided by 2 is -3.5. Removing the decimal part would give -3, but -3 is above -3.5. The next integer below -3.5 is -4, so that is what floor division returns.

04Operator precedence

You now know how each arithmetic operator works on its own. But what happens when you use several of them in the same expression? Which operation does Python perform first?

Take a practical example: body mass index. The formula is weight in kilograms divided by the square of height in meters. Suppose someone weighs 70 kilograms and is 1.75 meters tall. In Python you could write:

70 / 1.75 ** 2

Does Python evaluate this from left to right? If it did, it would divide 70 by 1.75 first, and then square the result. Written with parentheses to force that order, it looks like this:

(70 / 1.75) ** 2
1600.0
Predict first

That would give 1,600. Is that what Python does with the original expression? Think it through before reading on.

I have a guess. Show meHide the answer
70 / 1.75 ** 2
22.857142857142858

It does not give 1,600. The two operations were grouped differently.

Operator precedence

Python does not simply evaluate every operator from left to right. It follows operator precedence: a set of rules that decides which operations are grouped together first. Some operators have higher precedence than others, and for the arithmetic operators in this lesson, exponentiation comes before multiplication and division.

So Python evaluates 1.75 ** 2 first:

1.75 ** 2
3.0625

Only then does it divide 70 by that result, which gives approximately 22.86.

The general order

From highest precedence to lowest:

  1. Exponentiation, **.
  2. Multiplication *, regular division /, floor division // and modulo %.
  3. Addition + and subtraction -.

When two operators have the same precedence

What happens when two operators have the same precedence? For most of the arithmetic operators you have met, Python groups them from left to right. So a - b + c means (a - b) + c.

Predict first

Exponentiation is the exception. It groups from right to left, so a ** b ** c means a ** (b ** c). What do you think 2 ** 3 ** 2 gives? Think it through before reading on.

I have a guess. Show meHide the answer
2 ** 3 ** 2
512

Python works out 3 ** 2 first, which is 9, and then 2 ** 9, which is 512. Grouping from left to right would have given (2 ** 3) ** 2, which is 8 ** 2, or 64.

Parentheses

This brings you to something very useful: parentheses. Parentheses let you control how an expression is grouped. When you put part of an expression inside parentheses, Python evaluates that part first:

70 / (1.75 ** 2)
22.857142857142858

This is the same grouping Python used for 70 / 1.75 ** 2, but now nobody reading the code has to remember the precedence rules to see it. So whenever an expression becomes difficult to read, do not hesitate to use parentheses, even if Python would evaluate it correctly without them. Clear code is always better than clever-looking code.

05Comparison operators

So far you have been calculating numbers. Comparison operators let you ask questions about values instead. The result of a comparison is a Boolean: either True or False.

For example, suppose a variable called age holds the value 17, and you want to check whether someone is at least 18 years old:

age = 17
age >= 18
False

Python returns False, because 17 is not greater than or equal to 18.

The comparison operators

Python has six comparison operators:

OperatorChecks whether the left value is
==equal to the right value
!=not equal to the right value
<less than the right value
>greater than the right value
<=less than or equal to the right value
>=greater than or equal to the right value

To check whether two values are equal, you use two equals signs. To check whether they are not equal, you use an exclamation mark followed by an equals sign.

One equals sign or two

There is one mistake beginners make all the time: confusing one equals sign with two. A single equals sign assigns:

age = 18
age
18

age = 18 makes the name age refer to the value 18. It does not ask a question. Two equals signs compare:

age == 18
True

age == 18 checks whether age is equal to 18, and returns a Boolean. They are two completely different operations: = assigns, == compares values.

Chained comparisons

Python also lets you chain comparisons. Suppose you want to check whether someone's age is between 13 and 19, including both endpoints. You can write it in one line:

age = 17
13 <= age <= 19
True

With age at 17, Python returns True, because 17 is greater than or equal to 13 and less than or equal to 19. A chained comparison checks both of those at once, and because the operators are <=, the endpoints 13 and 19 are included.

06Logical operators

Sometimes one condition is not enough, and you need to check several conditions together. That is what logical operators are for. Python has three of them: and, or and not.

and

When you combine Boolean conditions, and gives True only when both conditions are True.

For example, suppose someone can vote only if they are at least 18 years old and they are a citizen. You can check both conditions with and. If the person is 19 and is a citizen:

age = 19
is_citizen = True
age >= 18 and is_citizen
True

Both conditions are True, so the combined condition is True. But if either condition is False, the whole condition is False. Here the age condition fails:

age = 17
age >= 18 and is_citizen
False

And here the citizenship condition fails:

age = 19
is_citizen = False
age >= 18 and is_citizen
False

or

or works differently. With or, the combined condition is True when at least one of the conditions is True. It is only False when both conditions are False.

not

Finally, not reverses the truth value of a condition:

not True
False
not False
True

Short-circuit evaluation

There is something interesting about how Python evaluates and and or: it does not always evaluate both sides.

Take and. If the first condition is already False, there is no way the overall condition can be True. So Python does not need to evaluate the second condition. It simply stops.

With or, if the first condition is already True, the overall condition is already satisfied, so Python skips the second condition.

This behavior is called short-circuit evaluation, and it is useful because it saves unnecessary work. You can see that the second side really is skipped. In the cell below, missing_name has never been defined, so evaluating it would raise a NameError. Python never gets that far:

False and missing_name, True or missing_name
(False, True)

and and or return an operand

Here is something that might surprise you. In Python, and and or do not always return True or False. They can return one of the operands themselves.

Suppose a variable called username holds an empty string:

username = ""
Predict first

Now write username or "Guest". What do you think Python returns? Think it through before reading on.

I have a guess. Show meHide the answer

An empty string counts as false in a Boolean context. You can see that by converting it with bool:

bool(username)
False

So the first operand of or is false, and Python goes on to evaluate the right-hand side. And it returns that right-hand operand:

username or "Guest"
'Guest'

When the left operand is true

What if username contains "Asha"?

username = "Asha"
username or "Guest"
'Asha'

Python returns 'Asha'. A non-empty string counts as true, so or stops at the first operand and returns it.

This is a pattern you will see quite often in Python. It lets you provide a default value for when the original value is empty or otherwise false. The important thing to understand is that and and or use truth values to decide where to stop, but they return the operand they stopped at, which is not necessarily a Boolean.

Bitwise operators

Python also has bitwise operators. These include symbols like the ampersand, &, and the vertical bar, |. They operate on the binary representation of integers. You will also meet these symbols when working with arrays in libraries like NumPy. Their behavior is covered in the lessons where you need them.

07Augmented assignment

You have already used the basic assignment operator, the equals sign. Python also gives you shorter ways to update a variable.

Suppose you have a balance of 100, and you want to subtract 25. You could write:

balance = 100
balance = balance - 25
balance
75

That works perfectly well. But Python also lets you write it like this:

balance = 100
balance -= 25
balance
75

This is called augmented assignment. For a number like this, it has the same effect: the balance becomes 75.

You can do something similar with addition, multiplication, division and the other arithmetic operators. So you will see += (plus equals), *= (times equals), /= (divide equals) and others in Python code. They make common updates shorter and easier to read.

08Identity and membership

In the variables lesson you used is to check whether two names refer to the same object. is not checks the opposite. Now compare identity with value equality, which uses ==.

is against ==

Suppose you write price = 1000.0, and then create another float from the string "1000.0":

price = 1000.0
other_price = float("1000.0")

Both objects represent the same numerical value. So if you compare them with ==, Python returns True, because their values are equal:

price == other_price
True

But what happens if you compare them with is?

price is other_price
False

You get False, because they are two different objects that happen to hold the same value. In everyday Python code, you will usually use == when comparing values.

Checking for None

One of the most common uses of is is checking for None:

rating = None
rating is None, rating is not None
(True, False)

rating is None checks whether rating refers to the None object. There is only ever one None object in Python (it is a singleton), so an identity check with is is the recommended way to test for it.

Membership with in and not in

There is one more group of operators to cover: the membership operators, in and not in. They check whether a value is contained within another object. With strings, for example, in checks whether one piece of text appears inside another.

Suppose you have an email address, "ana@example.com", and you want to check whether it contains the at sign:

"@" in "ana@example.com"
True

Python returns True, because the at sign is present in the string. not in asks the opposite question:

'@' in "ana@example.com", '@' not in "ana@example.com"
(True, False)

This does not mean the email address is valid. It only tells you that the character appears somewhere in the text. Later in the course you will use in and not in with lists, dictionaries and other collection types too.

09Recap and challenge

When you read an expression, identify its operators and operands, work out the grouping, and predict both the value and the type.

  • The seven arithmetic operators are +, -, *, /, //, % and **. Regular division with / always gives a float, and mixing an integer with a float generally gives a float.
  • Floor division // rounds down toward negative infinity, so -7 // 2 is -4. Modulo % gives the remainder.
  • ** runs before *, /, // and %, which run before + and -. Operators of equal precedence group from left to right, except **, which groups from right to left. Parentheses make the grouping explicit.
  • Comparison operators return True or False, and = assigns while == compares.
  • and, or and not combine conditions. and and or short-circuit, and return the operand they stopped at.
  • Augmented assignment, like balance -= 25, updates a variable in one step.
  • is checks identity, == checks value, and in checks membership.

Your challenge

Remember how you converted the workout duration from seconds into hours, minutes and seconds? Do the same thing, but this time with 10,000 seconds:

seconds = 10000
# Complete hours: use floor division
# Remaining minutes and seconds: use modulo
# Print your result with clear labels

Your program should calculate the number of complete hours, the remaining minutes and the remaining seconds. Use floor division and modulo to do it, and solve it with what you have learned about operators in this lesson.

In the next lesson, you will take the Boolean conditions from this lesson and use them to control which parts of a program actually run, with if, elif and else.