In Python, there are lots of operators.
You can use operators to do basic math, comparisons, logical expressions, and more.
Operators are an important concept in programming.
Here are some examples of using different types of operators in Python:
sum = 1 + 2 prod = 50 * 3 isLess = 1 < 2 isGreaterOrEqual = 100 >= 5 bothEqual = 1 == 1 and 5 == 5 pythonIsEasy = not False
This is a complete guide to operators in Python. The theory is backed up with great and illustrative examples.
In Python, you can use arithmetic operators to do basic math.
Some of these operators are probably familiar to you from elementary school maths. And the ones that are not are still pretty straightforward to understand.
Here is a quick cheat sheet of the arithmetic operators in Python:
|Addition||Adds up variables a and b.|
|Subtraction||Subtracts variable b from a.|
|Multiplication||Multiplies a by b.|
|Division||Divides a by b.|
|Modulo||Gives the remainder in the division between a and b.|
|Floor Division (also called Integer Division)||Divides a by b and rounds the result to the smallest whole number.|
|Exponentiation||Raises a to the power of b.|
Let’s have a closer look at how to use each of these operators with examples.
The addition operator (+) sums up two numeric values.
It is a binary operator because it takes two values to operate on.
sum = 1 + 2 print(sum)
Unary + Operator
Similar to mathematics, you can also use the + operator as a unary operator in Python.
This means you place it in front of a single number to highlight the positivity of a value.
temperature = +30 print(temperature)
However, you are never going to use the unary + because, practically, it does not do anything.
The subtraction operator (-) subtracts one value from another.
diff = 1 - 2 print(sum)
Unary – Operator
You can also use the – operator as a unary operator in Python by placing it in front of a numeric value.
This changes the sign of the number.
- A positive value becomes negative.
- A negative value becomes positive.
n = -10 p = -n print(p)
The multiplication operator (*) multiplies two values.
prod = 10 * 3 print(prod)
The division operator (/) divides two values.
fraction = 10.0 / 4.0 print(fraction)
In math, a modulo returns the remainder in the division.
For instance, 7 mod 2 = 1. You cannot evenly divide 7 to 2. Instead, there will be one leftover.
In Python, the modulo operator is the “percent sign” operator %.
For example, let’s calculate leftover pizza slices with the modulo operator:
pizzaSlices = 15 eaters = 4 leftoverSlices = 15 % 4 print(leftoverSlices)
The result is three because there is no way to evenly share 15 slices of pizza among a group of 4. To fairly share the slices, everyone gets 3 slices, that is, 12 are shared. Then 3 slices are leftover.
Floor division means dividing two numeric values and rounding down to the nearest whole number.
result = 10 // 3 print(result)
The result is 3 because 10 / 3 = 3.33 and the nearest whole number below this value is 3.
Notice that the floor division always rounds down!
Let me show you another example:
result = 10 // 6 print(result)
The result of 10 / 6 is 1.6667 and the next whole number below this value is 1.
So even though rounding 1.6667 would normally round up to 2, floor division squashes it down.
Exponentiation means raising a number to a power.
When you raise a number to a power, you multiply the number by itself as many times as the exponent states.
For instance, 2³ = 2 * 2 * 2 = 8.
In Python, the exponentiation operator (or power) is denoted with a double multiplication operator (**).
result = 4 ** 3 print(result)
This is equivalent to 4 * 4 * 4.
Shorthand Assignment Operators
In Python, it is common to update existing values.
For instance, let’s create a counter variable at 0 and start incrementing it:
counter = 0 counter = counter + 1 counter = counter + 1 counter = counter + 1 print(counter)
Because updating an existing value like this is such a common operation to do, there is a shorthand to it.
This is called shorthand assignment in Python.
It happens by combining the assignment operator (=) and the arithmetic operator (+, -, *, /, **, %, //).
For example, let’s repeat the counter example but let’s use a shorthand assignment when adding values to the counter:
counter = 0 counter += 1 counter += 1 counter += 1 print(counter)
Here counter += 1 is equivalent to counter = counter + 1.
Here are more examples with other arithmetic operators:
s = 0 s += 1 print(s) # s is now 1 d = 10 d -= 5 print(d) # d is now 5 m = 5 m *= 10 print(m) # m is now 50 n = 10 n /= 2 print(n) # n is now 5.0 x = 16 x %= 6 print(x) # x is now 4 y = 10 y //= 4 print(y) #y is now 2 z = 4 z **= 3 print(z) #z is now 64
Next, let’s discuss comparison operators.
In Python, you will deal with data all the time.
It is thus common to need to perform comparisons between the data.
To make comparisons, there are 6 comparison operators you can use in Python.
These comparisons are something you are probably familiar with from elementary school math.
Here is a quick cheat of the comparison operators:
|Equal to||If the value of a is equal to the value of b returns True.|
Otherwise, returns False.
|Not equal to||If the value of a is not equal to the value of b returns True.|
Otherwise, returns False.
|Less than||If a is less than b, returns True.|
Otherwise returns False.
|Less than or equal to||If a is less than or equal to b, returns True.|
Otherwise returns False.
|Greater than||If a is greater than b, returns True.|
Otherwise returns False.
|Greater than or equal to||If a is greater than or equal to b, returns True.|
Otherwise returns False.
Let’s take a look at each comparison operator separately.
The Equal to Operator (==)
The equal to operator checks if two values are equal to one another.
The equality operator is denoted with a double equals sign.
You may ask why double equals and not a single equals.
This is because the single equal sign is reserved for the assignment operation.
For example, let’s compare two numbers:
a = 10 b = 10 print(a == b)
Notice that you can perform a similar equality comparison between strings as well:
name1 = "Alice" name2 = "Alice" print(name1 == name2)
The Not Equal to Operator (!=)
To negate the equality operator, replace the first equals sign with an exclamation mark.
This gives rise to a new operator called the not equal operator.
If two compared values are not equal to one another, the not equal operator returns True.
a = 10 b = 10 print(a != b)
The Less Than Operator (<)
To check if a value is less than another value, use the less-than operator (<) by placing it between two comparable values.
result = 1 < 2 print(result)
The Less Than or Equal to Operator (<=)
Sometimes you are interested if the value is either less than or equal to another value.
In this case, you can use the less than or equal operator (<=) which is a combination of the less-than operator and the equal operator.
print(2 <= 2)
The Greater Than Operator (>)
To check if a value is greater than another, use the greater-than operator (>) by placing it between two comparable values.
print(20 > 2)
The Greater Than or Equal to Operator (>=)
Sometimes you are interested if the value is either greater than or equal to another value.
In this case, you can use the greater than or equal operator (>=) which is a combination of the greater-than operator and the equal operator.
result = 8 >= 3 print(result)
With the basics of comparison operators out of the way, let’s talk about confusing misbehavior related to comparing floating-point numbers.
Precision Inaccuracy When Comparing Floats
Take a look at this piece of code where we compare two floating-point numbers:
print(3.6 == 1.3 + 2.3)
Clearly, this comparison should be True.
But it appears to be False according to Python.
This is due to floating-point inaccuracy.
A computer does not have enough space to represent specific floats numbers precisely.
Think about a number like 1/3. The decimal representation of it is 0.333333333… where 3 repeats forever. To precisely write down this number, you would need to repeat 3 forever. This is obviously not possible.
Similar logic applies to floating-point precision in Python.
A computer uses a binary system to represent numbers.
Similar to our 10-base system, in a binary system, there are some values that repeat forever. To store one precisely, a computer would need infinite memory.
Because this is not possible, these types of decimal values are cut short, which causes imprecision.
Thus some floating-point numbers are inaccurate by a small amount.
Due to this precision error, comparing floating-point numbers with the equality operator is meaningless.
To check the equality of two floats, you should check if a number is really close to some value instead.
Given small inaccuracies in a and b, if the values are equal to one another, their difference is close to zero.
tolerance = 0.000001 areEqual = abs((1.3 + 2.3) - 3.6) < tolerance print(areEqual)
Because the absolute value of the difference between 1.3 + 2.3 and 3.6 is smaller than the 0.000001, the numbers must be really close to one another. In other words, they are equal.
Notice that floating-point inaccuracy is not a Python-specific thing. It is present in all programming languages.
In Python, you can combine logical expressions with logical operators.
Logical operators are used in everyday life as we speak.
Have a look at this sentence: “If it is hot and sunny, let’s go to the beach”.
Although you may not think about it, this very sentence uses a logical “and” operator to combine two logical expressions.
Let’s rephrase the sentence to better understand what it means:
“If it is a sunny day and if it is a hot day, let’s go to the beach”.
Now, let’s split this sentence into three parts:
- It is a sunny day
- It is a hot day
The first part, “It is a sunny day” is a logical expression. The outcome is either true or false.
The word “and” is a logical operator. It connects the first and the second one.
The second sentence, “It is a hot day” is the second logical expression that is also either true or false.
If both of these logical expressions are true, we go to the beach. Otherwise, we don’t.
This is the idea of logical expressions and logical operators in a nutshell.
Now, let’s take a look at the logical operators in Python.
Logical Expressions with Boolean Operands
In Python, there are three logical operators:
Here is a cheat sheet to quickly see how they work:
|Reverses the truth.|
False –> True
True –> False
|True if either x or y is True.|
|True if both x and y are True.|
Now that you understand how logical operators work in Python, let’s turn the real-life example above into Python code:
isSunny = True isHot = False beachTime = isSunny and isHot print(beachTime)
Let’s see another example.
In this example, the person is busy if they are either working or studying:
isStudying = False isWorking = True isBusy = isStudying or isWorking print(isBusy)
As you can see, even though isStudying is False, the person is still busy because isWorking is True.
Let’s also see an example of using the not operator.
The not operator negates the boolean value, so that True becomes False and vice versa.
isRainy = True isSunny = not isRainy print(isSunny)
As you can see, it is not sunny because it is rainy.
Notice that you can use logical operators to combine any Boolean values in Python.
For instance, you can combine the results of two (or more) comparisons:
print(1 == 2 or 10 < 20)
In Python, objects and expressions are commonly something else than True or False.
However, these non-boolean values are still be considered “truthy” or “falsy” in a boolean context.
In other words, each non-boolean value in Python becomes either True or False in a boolean context.
For instance, the number 0 is False as a boolean value and 1 is True. As a matter of fact, any non-zero integer is “truthy”.
Here are all the values that are False in the boolean context:
- False itself.
- 0 and 0.0
- Empty strings.
- Empty composite data objects (you learn about these later on).
- None, which is a special object in Python that represents the absence of a value.
Anything other than these is True in a boolean context.
To convert a value to a boolean, use the built-in bool() function.
For example, let’s turn the number 0 to a boolean:
booleanZero = bool(0) print(booleanZero)
Logical Expressions with Non-Boolean Values
In the previous section, you learned that all values in Python are “truthy” or “falsy”.
This makes it possible to apply logical operators to non-boolean values as well.
This is best demonstrated with examples using different logical operators.
The “or” Operator with Non-Boolean Values
As you learned before, the or operator works such that it returns False only if both compared values are False. Otherwise, it always returns True.
result = True or False print(result)
Now, let’s jump out of boolean values and apply the or operator on two integers:
result = 0 or 1 print(result)
The result is 1 because, in the boolean context, 0 is “falsy” and 1 is “truthy”.
As you learned, the result of the or operator can only be “falsy” if both compared values are “falsy”.
In this particular case, the second value 1 is “truthy”. Thus the result is “truthy”.
Let’s see another example.
Let’s apply the or operator on two “truthy” values and see what we get:
result = 10 or 5 print(result)
The result is the first number.
This is due to what is called short-circuiting in Python.
In short, if the first value is True or “truthy”, the result of or operation is automatically True or “truthy” regardless of the second item. Thus the first item is the result.
You will learn more about short-circuiting in a bit.
The “and” Operator with Non-Boolean Values
Let’s repeat the above examples using the and operator.
As you learned before, the and operator returns True only if both compared values are True. Otherwise, it always returns False.
result = True and False print(result)
Now, let’s apply the and operator between two integer values:
result = 1 and 0 print(result)
The result is 0 because in the boolean context 0 is “falsy” and 1 is “truthy”. Furthermore, the result of the and operator can only be “truthy” if both compared values are “truthy”. Here the second value 0 is “falsy” so the result is “falsy”.
Let’s take a look at another example.
result = 10 and 5 print(result)
This time, the result is 5.
But why not 10?
The first number 10 is “truthy”. But it is not enough for the and operator to know whether the whole result should be “truthy” or “falsy”. Thus, the second number needs to be checked as well.
So the second number is the deciding factor. This also makes it the result of the operation.
If the first number was “falsy”, the and operator would have returned it because it would have been enough to know the result is “falsy”.
No worries if this sounds confusing, you will learn about this process in a minute.
Before going there, let’s quickly see an example with the not operator as well.
The “not” Operator with Non-Boolean Values
The not operator directly converts “truthy” values to False and “falsy” values to True.
result = not 10 print(result)
The result is False because 10 is “truthy” in a boolean context. The not operator inverts the value to “falsy” and returns False.
Let’s see another similar example:
result = not 0.0 print(result)
In boolean context, 0.0 is “falsy” or False. Thus the not operator converts it to True.
Now, let’s learn more about short-circuiting.
Short-Circuit Evaluation and Operator Chaining
In the previous examples, you learned how to create simple logical expressions by combining two expressions with a logical operator.
truth = False or True
But you can also form longer chains of logical operators if needed.
Take a look at this chain of or operators:
v1 or v2 or v2 or ... vN
This whole expression is True if a single vN happens to be True.
The way Python determines the result is interesting and it has really neat applications.
This is called the short-circuit evaluation.
In a logical operator chain, the values are evaluated from left to right.
In a chain of or operators, as soon as one of the values is True, no more values are checked because the result is known to be True already.
Here is the important part: The short-circuit evaluation returns the value that terminated the evaluation.
result = True or False or False or False or False print(result)
Here Python starts by checking the first value. Because it is True, there is no reason to continue evaluating the other values.
Let’s see a similar example with non-boolean values. This example demonstrates the short-circuiting better:
result = 0 or 0 or 3 or 0 or 0 print(result)
The result of this expression is 3.
Here is how the result is calculated:
- Python starts by evaluating the first value. It is 0 so it is “falsy” in a boolean context.
- The same applies to the second value.
- But the 3rd value is “truthy” as a non-zero value. Python now knows the whole expression is “truthy” regardless of the rest of the values. Here deciding factor was 3 so it is the final result as well.
The short-circuiting applies to chains of and operators as well.
Have a look at this chain of and operators:
v1 and v2 and v2 and ... vN
By definition, this whole expression is True only if all the values vN are True.
When Python encounters this type of chain, the values are evaluated from left to right. As soon as one of the values is False, no more values are checked because the result is automatically False.
The same logic applies to chains of non-boolean values. The result is the value that terminated the evaluation.
To make sense of this, let’s see a bunch of examples.
result = True and True and False and True print(result)
In this expression:
- Python evaluates the first value. Because it is True, the evaluation continues.
- The same goes for the second value.
- The third value is False. Thus the whole expression is False no matter what the rest of the values are.
Let’s see a similar example with non-boolean values:
result = 45 and 0 and 322 and 98 print(result)
This evaluation of this expression terminates at the number 0.
This is because 0 is “falsy”.
If there is any “falsy” in a chain of and operators, the result must be “falsy”.
The value that terminates the evaluation is the result.
In this case, it is the number 0.
How to Use Short-Circuit Evaluation in Python
In addition to being an implementation detail of Python, there are some applications to short-circuit evaluation in Python.
The two most common ways to use short-circuit evaluation are:
- Avoiding errors
- Picking default values
Let’s briefly go through both of these.
Avoiding Errors with Short-Circuit Evaluation
Let’s divide two values x and y:
x = 10 y = 5 result = x / y print(result)
No problem with this piece of code.
This is not a surprise because dividing two numbers is a legal operation.
But if you recall from elementary math, you cannot divide by 0.
If you divide by 0 in Python, your program crashes with an error.
x = 10 y = 0 result = x / y print(result)
ZeroDivisionError: division by zero
You can avoid an error like this by using the short-circuit evaluation.
In the previous section, you learned that the and operator is short-circuited so that if a value is False, the evaluation stops.
Let’s use this idea to protect from division by 0:
x = 10 y = 0 result = y != 0 and x / y print(result)
As you can see, even though there is a division by 0, the program did not crash. Instead, the result is False.
To understand why let’s inspect this expression:
y != 0 and x / y
Due to short-circuit evaluation, if y != 0 is False, the result of the whole expression is False. The key is that the right-most expression is never evaluated so the division by 0 never takes place.
But if the value of y is non-zero, the first condition is True and the right-most expression gets evaluated and is the result.
x = 10 y = 5 result = y != 0 and x / y print(result)
Because y != 0 returns True, the evaluation continues to x / y, which terminates the expression and returns the result of the division.
This is one example of a useful application of the short-circuit evaluation in Python.
Before moving on, let’s see another one.
Picking a Default Value with Short-Circuit Evaluation
Another useful way to use the short-circuit evaluation in Python is to pick a default value.
Let’s see an example.
name = "" or "there" print("Hello", name)
Here the left-most string is an empty string, thus the default value “there” is used.
Take a look at this expression:
"" or "there"
As you learned before, in a boolean context, an empty string is considered “falsy”.
The or operator works such that it continues evaluating the expression until it encounters True or “truthy”.
In this case, the first string is “falsy”. The evaluation continues to the second string which becomes the result of the expression.
If the first string is non-empty, it is “truthy”. Thus the evaluation of the expression stops and the first string is the result:
name = "Alice" or "there" print("Hello", name)
Now that you have learned about comparison operators and logical operators, it is time to learn a neat shorthand for chaining comparisons.
For example, let’s check if a number is less than 1000 and greater than 10:
value = 10 isInRange = value < 1000 and value > 0 print(isInRange)
This piece of code works just fine.
However, you can make the comparisons more readable by chaining them together instead of writing them as two separate comparisons.
Here is how it looks:
value = 10 isInRange = 0 < value < 1000 print(isInRange)
This expression is easier to read. Furthermore, it resembles the way you check ranges in mathematics.
In addition to the basic numerical operators we talked about earlier in this chapter, Python has operators to perform bitwise operations on integers.
Bitwise operators are far less commonly used than the basic math operators.
Thus, we are not going deep into the details of them.
However, it is useful to know such operators exist.
Here is a quick cheat sheet for bitwise operators in Python.
|bitwise AND||Logical AND operation between each bit in the corresponding position between the bit sequences.|
|bitwise OR||Logical OR operation between each bit in the corresponding position between the bit sequences.|
|bitwise negation||Logical negation between each bit in the corresponding position between the bit sequences.|
|bitwise XOR (exclusive OR)||Logical XOR operation between each bit in the corresponding position between the bit sequences.|
|Shift right ||Each bit shifted to the right by |
|Shift left ||Each bit shifted to the left by |
In Python, you can check the unique ID of an object using the id() function.
For instance, to check if two variables refer to the same object, check if their IDs match.
x = 10 y = x print(id(x) == id(y))
This reveals that both x and y point to the same object in memory.
But instead of using the id() function, there are two dedicated operators to this:
- The is operator can be used to check if two objects have the same ID.
- The is not operator can be used to check if two objects have a different ID.
Let’s repeat the above example using the is operator:
x = 10 y = x print(x is y)
This approach is cleaner and easier to read compared to using the id() function.
Now that you have seen all the basic operators in Python, let’s discuss the evaluation order or the precedence of these operators.
Operator Precedence in Python
As you learned in elementary school, not all math operators are equal.
Operators + and – are evaluated after * or /.
The concept that determines the evaluation order of operators is called the precedence.
Precedence states which operator precedes which.
The same logic applies to Python.
result = 1 + 10 * 3 - 8 / 2 print(result)
Let’s visualize the precedence of these operations with parenthesis:
result = 1 + (10 * 3) - (8 / 2) = 1 + 30 - 4 = 27
Understanding the precedence of the arithmetic operators is important. Also, knowing the precedence of the logical operators (or, and, not) is useful.
You don’t have to worry about the precedence of the other operators nearly as much if not at all.
But if you have to, here is a full precedence chart of all the operators in Python.
The lower the operator, the lower the precedence.
In this guide, you learned about operators in Python.
To recap, the arithmetic operators allow you to do basic math in Python.
Comparison operators make it possible to compare data.
Logical operators allow you to connect logical expressions, such as comparisons.
Bitwise operators allow you to operate on integers on a bit-level.
The identity operators let you check if two objects are the same object in memory.
All the operators in Python belong to a precedence group. This determines which operations take place first if combined with other operators.
Thanks for reading.