Operators and Expressions in Python Real Python
Operators and Expressions in Python Real Python
Table of Contents
Arithmetic Operators
Comparison Operators
Equality Comparison on Floating-Point Values
Logical Operators
Logical Expressions Involving Boolean Operands
Evaluation of Non-Boolean Values in Boolean Context
Logical Expressions Involving Non-Boolean Operands
Compound Logical Expressions and Short-Circuit Evaluation
Idioms That Exploit Short-Circuit Evaluation
Chained Comparisons
Bitwise Operators
Identity Operators
Operator Precedence
Augmented Assignment Operators
Conclusion
A er finishing our previous tutorial on Python variables in this series, you should now have a good grasp of creating
and naming Python objects of di erent types. Let’s do some work with them!
Here’s what you’ll learn in this tutorial: You’ll see how calculations can be performed on objects in Python. By the
end of this tutorial, you will be able to create complex expressions by combining objects and operators.
Take the Quiz: Test your knowledge with our interactive “Python Operators and Expressions” quiz. Upon
completion you will receive a score so you can track your learning progress over time:
https://realpython.com/python-operators-expressions/ 1/22
6/28/2019 Operators and Expressions in Python – Real Python
In Python, operators are special symbols that designate that some sort of computation should be performed. The
values that an operator acts on are called operands.
Here is an example:
Python >>>
>>> a = 10
>>> b = 20
>>> a + b
30
>>> a = 10
>>> b = 20 Email Address
>>> a + b - 5
25
Send Python Tricks »
A sequence of operands and operators, like a + b - 5, is called an expression. Python supports many operators for
combining data objects into expressions. These are explored below.
Arithmetic Operators
The following table lists the arithmetic operators supported by Python:
// a // b Floor Division (also Quotient when a is divided by b, rounded to the next smallest
called Integer whole number
Division)
Python >>>
>>> a = 4
>>> b = 3
>>> +a
4
Improve Your Python
>>> -b
https://realpython.com/python-operators-expressions/ 2/22
6/28/2019 Operators and Expressions in Python – Real Python
-3
>>> a + b
7
>>> a - b
1
>>> a * b
12
>>> a / b
1.3333333333333333
>>> a % b
1
>>> a ** b
64
>>> 10 / 5
2.0 Email Address
>>> type(10 / 5)
<class 'float'>
Python >>>
>>> 10 / 4
2.5
>>> 10 // 4
2
>>> 10 // -4
-3
>>> -10 // 4
-3
>>> -10 // -4
2
Note, by the way, that in a REPL session, you can display the value of an expression by just typing it in at the >>>
prompt without print(), the same as you can with a literal value or variable:
Python >>>
>>> 25
25
>>> x = 4
>>> y = 6
>>> x
4
>>> y
6
>>> x * 25 + y
106
Comparison Operators
Operator Example Meaning Result
https://realpython.com/python-operators-expressions/ 3/22
6/28/2019 Operators and Expressions in Python – Real Python
<
Operator a < b
Example Less than
Meaning True if a is less than b
Result
False otherwise
>>> a = 30
>>> b = 30
>>> a == b
True
>>> a <= b
True
>>> a >= b
True
Comparison operators are typically used in Boolean contexts like conditional and loop statements to direct program
flow, as you will see later.
Python >>>
Yikes! The internal representations of the addition operands are not exactly equal to 1.1 and 2.2, so you cannot rely
on x to compare exactly to 3.3.
The preferred way to determine whether two floating-point values are “equal” is to compute whether they are close
to one another, given some tolerance. Take a look at this example:
Python >>>
abs() returns absolute value. If the absolute value of the di erence between the two numbers is less than the
Improve Your Python
specified tolerance, they are close enough to one another to be considered equal.
https://realpython.com/python-operators-expressions/ 4/22
6/28/2019 Operators and Expressions in Python – Real Python
Logical Operators
The logical operators not, or, and and modify and join together expressions evaluated in Boolean context to create
more complex conditions.
>>> callable(x)
False
>>> type(callable(x))
<class 'bool'>
>>> t = callable(len)
>>> t
True
>>> type(t)
<class 'bool'>
In the examples above, x < 10, callable(x), and t are all Boolean objects or expressions.
Interpretation of logical expressions involving not, or, and and is straightforward when the operands are Boolean:
x = 5
not x < 10
False Improve Your Python
t ll bl ( )
https://realpython.com/python-operators-expressions/ 5/22
6/28/2019 Operators and Expressions in Python – Real Python
not callable(x)
True
x = 5
x < 10 and callable(x)
False
x < 10 and callable(len)
True
So what is true and what isn’t? As a philosophical question, that is outside the scope of this tutorial!
But in Python, it is well-defined. All the following are considered false when evaluated in Boolean context:
Numeric Value
A zero value is false.
A non-zero value is true.
Python >>>
Python >>>
The examples below demonstrate this for the list type. (Lists are defined in Python with square brackets.)
For more information on the list, tuple, dict, and set types, see the upcoming tutorials.
Python >>>
>>> type([])
<class 'list'>
>>> bool([])
False
Python >>>
>>> bool(None)
False
Non-Boolean values can also be modified and joined by not, or and, and. The result depends on the “truthiness” of the
operands.
If x is not x is
“truthy” False
Improve Your Python
“falsy” True
...with a fresh 🐍 Python Trick 💌
code snippet every couple of days:
Here are some concrete examples:
>>> x = 3
>>> bool(x)
True Send Python Tricks »
>>> not x
False
>>> x = 0.0
>>> bool(x)
False
>>> not x
True
If x is x or y is
truthy x
falsy y
Note that in this case, the expression x or y does not evaluate to either True or False, but instead to one of either x or
y:
Python >>>
>>> x = 3
>>> y = 4
>>> x or y
3
>>> x = 0.0
>>> y = 4.4
>>> x or y
4.4
Even so, it is still the case that the expression x or y will be truthy if either x or y is truthy, and falsy if both x and y are
falsy.
If x is x and y is
Improve Your Python
https://realpython.com/python-operators-expressions/ 8/22
6/28/2019 Operators and Expressions in Python – Real Python
“truthy” y
If x is x and y is
“falsy” x
Python >>>
>>> x = 3
>>> y = 4
>>> x and y
4
>>> x = 0.0
Python
x or y
x and y
Multiple logical operators and operands can be strung together to form compound logical expressions.
x1 or x2 or x3 or … xn
In an expression like this, Python uses a methodology called short-circuit evaluation, also called McCarthy evaluation
in honor of computer scientist John McCarthy. The xi operands are evaluated in order from le to right. As soon as
one is found to be true, the entire expression is known to be true. At that point, Python stops and no more terms are
evaluated. The value of the entire expression is that of the xi that terminated evaluation.
To help demonstrate short-circuit evaluation, suppose that you have a simple “identity” function f() that behaves as
follows:
(You will see how to define such a function in the upcoming tutorial on Functions.)
Python >>>
>>> f(0)
-> f(0) = 0
0
>>> f(False)
-> f(False) = False
False
>>> f(1.5)
-> f(1.5) = 1.5 Improve Your Python
https://realpython.com/python-operators-expressions/ 9/22
6/28/2019 Operators and Expressions in Python – Real Python
1.5
Because f() simply returns the argument passed to it, we can make the expression f(arg) be truthy or falsy as
needed by specifying a value for arg that is appropriately truthy or falsy. Additionally, f() displays its argument to the
console, which visually confirms whether or not it was called.
Python >>>
Next up is f(1). That evaluates to 1, which is true. At that point, the interpreter stopsSend Python
because Tricks
it now knows» the entire
expression to be true. 1 is returned as the value of the expression, and the remaining operands, f(2) and f(3), are
never evaluated. You can see from the display that the f(2) and f(3) calls do not occur.
In this case, short-circuit evaluation dictates that the interpreter stop evaluating as soon as any operand is found to be
false, because at that point the entire expression is known to be false. Once that is the case, no more operands are
evaluated, and the falsy operand that terminated evaluation is returned as the value of the expression:
Python >>>
In both examples above, evaluation stops at the first term that is false—f(False) in the first case, f(0.0) in the second
case—and neither the f(2) nor f(3) call occurs. False and 0.0, respectively, are returned as the value of the
expression.
If all the operands are truthy, they all get evaluated and the last (rightmost) one is returned as the value of the
expression:
Python >>>
https://realpython.com/python-operators-expressions/ 10/22
6/28/2019 Operators and Expressions in Python – Real Python
Avoiding an Exception
Suppose you have defined two variables a and b, and you want to know whether (b / a) > 0:
Python >>>
>>> a = 3
>>> b = 1
>>> (b / a) > 0 Improve Your Python
True
...with a fresh 🐍 Python Trick 💌
code snippet every couple of days:
But you need to account for the possibility that a might be 0, in which case the interpreter will raise an exception:
>>> a = 0
>>> b = 1
>>> (b / a) > 0 Send Python Tricks »
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
(b / a) > 0
ZeroDivisionError: division by zero
Python >>>
>>> a = 0
>>> b = 1
>>> a != 0 and (b / a) > 0
False
When a is 0, a != 0 is false. Short-circuit evaluation ensures that evaluation stops at that point. (b / a) is not
evaluated, and no error is raised.
If fact, you can be even more concise than that. When a is 0, the expression a by itself is falsy. There is no need for the
explicit comparison a != 0:
Python >>>
>>> a = 0
>>> b = 1
>>> a and (b / a) > 0
0
Python
s = string or '<default_value>'
If string is non-empty, it is truthy, and the expression string or '<default_value>' will be true at that point.
Improve Your Python
Evaluation stops, and the value of string is returned and assigned to s:
https://realpython.com/python-operators-expressions/ 11/22
6/28/2019
g
Operators and Expressions in Python – Real Python
Python >>>
On the other hand, if string is an empty string, it is falsy. Evaluation of string or '<default_value>' continues to the
next operand, '<default_value>', which is returned and assigned to s:
Python >>>
Email Address
Chained Comparisons
Comparison operators can be chained together to arbitrary length. For example, theSend
following expressions
Python Tricks » are nearly
equivalent:
Python
x < y <= z
x < y and y <= z
They will both evaluate to the same Boolean value. The subtle di erence between the two is that in the chained
comparison x < y <= z, y is evaluated only once. The longer expression x < y and y <= z will cause y to be evaluated
twice.
Note: In cases where y is a static value, this will not be a significant distinction. But consider these expressions:
Python
If f() is a function that causes program data to be modified, the di erence between its being called once in the
first case and twice in the second case may be important.
More generally, if op1, op2, …, opn are comparison operators, then the following have the same Boolean value:
In the former case, each xi is only evaluated once. In the latter case, each will be evaluated twice except the first and
last, unless short-circuit evaluation causes premature termination.
Bitwise Operators
Bitwise operators treat operands as sequences of binary digits and operate on them bit by bit. The following
operators are supported:
& a & b bitwise Each bit position in the result is the logical AND of the bits in the
AND corresponding position of theYour
Improve operands.
Python(1 if both are 1, otherwise 0.)
https://realpython.com/python-operators-expressions/ 12/22
6/28/2019 Operators and Expressions in Python – Real Python
Operator
| Example
a | b bitwise
Meaning Each bit position in the result is the logical OR of the bits in the
Result
OR corresponding position of the operands. (1 if either is 1, otherwise 0.)
~ ~a bitwise Each bit position in the result is the logical negation of the bit in the
negation corresponding position of the operand. (1 if 0, 0 if 1.)
^ a ^ b bitwise Each bit position in the result is the logical XOR of the bits in the
XOR corresponding position of the operands. (1 if the bits in the operands are
(exclusive di erent, 0 if they are the same.)
OR)
Note: The purpose of the '0b{:04b}'.format() is to format the numeric output of the bitwise operations, to
make them easier to read. You will see the format() method in much more detail later. For now, just pay
attention to the operands of the bitwise operations, and the results.
Identity Operators
Python provides two operators, is and is not, that determine whether the given operands have the same identity—
that is, refer to the same object. This is not the same thing as equality, which means the two operands refer to objects
that contain the same data but are not necessarily the same object.
Here is an example of two object that are equal but not identical:
Python >>>
>>> x = 1001
>>> y = 1000 + 1
>>> print(x, y)
1001 1001
>>> x == y
True
>>> x is y
False
Here, x and y both refer to objects whose value is 1001. They are equal. But they do not reference the same object, as
you can verify:
Improve Your Python
https://realpython.com/python-operators-expressions/ 13/22
6/28/2019 Operators and Expressions in Python – Real Python
Python >>>
>>> id(x)
60307920
>>> id(y)
60307936
You saw previously that when you make an assignment like x = y, Python merely creates a second reference to the
same object, and that you could confirm that fact with the id() function. You can also confirm it using the is operator:
Python
Improve Your Python>>>
>>> a = 'I am a string'
>>> b = a ...with a fresh 🐍 Python Trick 💌
>>> id(a) code snippet every couple of days:
55993992
>>> id(b)
55993992 Email Address
>>> a is b
True Send Python Tricks »
>>> a == b
True
In this case, since a and b reference the same object, it stands to reason that a and b would be equal as well.
Python >>>
>>> x = 10
>>> y = 20
>>> x is not y
True
Operator Precedence
Consider this expression:
Python >>>
>>> 20 + 4 * 10
60
There is ambiguity here. Should Python perform the addition 20 + 4 first and then multiply the sum by 10? Or should
the multiplication 4 * 10 be performed first, and the addition of 20 second?
Clearly, since the result is 60, Python has chosen the latter; if it had chosen the former, the result would be 240. This is
standard algebraic procedure, found universally in virtually all programming languages.
All operators that the language supports are assigned a precedence. In an expression, all operators of highest
precedence are performed first. Once those results are obtained, operators of the next highest precedence are
performed. So it continues, until the expression is fully evaluated. Any operators of equal precedence are performed
in le -to-right order.
Here is the order of precedence of the Python operators you have seen so far, from lowest to highest:
Operator Description
not Boolean
Improve NOT
Your Python
https://realpython.com/python-operators-expressions/ 14/22
6/28/2019 Operators and Expressions in Python – Real Python
| bitwise OR
^ bitwise XOR
+, - addition, subtraction
Improve Your Python
*, /, //, % multiplication, division,
...withfloor division,
a fresh modulo
🐍 Python Trick 💌
code snippet every couple of days:
+x, -x, ~x unary positive, unary negation, bitwise negation
Email Address
highest precedence ** exponentiation
It is clear why multiplication is performed first in the example above: multiplication has a higher precedence than
addition.
Similarly, in the example below, 3 is raised to the power of 4 first, which equals 81, and then the multiplications are
carried out in order from le to right (2 * 81 * 5 = 810):
Python >>>
>>> 2 * 3 ** 4 * 5
810
Operator precedence can be overridden using parentheses. Expressions in parentheses are always performed first,
before expressions that are not parenthesized. Thus, the following happens:
Python >>>
>>> 20 + 4 * 10
60
>>> (20 + 4) * 10
240
>>> 2 * 3 ** 4 * 5
810
>>> 2 * 3 ** (4 * 5)
6973568802
In the first example, 20 + 4 is computed first, then the result is multiplied by 10. In the second example, 4 * 5 is
calculated first, then 3 is raised to that power, then the result is multiplied by 2.
There is nothing wrong with making liberal use of parentheses, even when they aren’t necessary to change the order
of evaluation. In fact, it is considered good practice, because it can make the code more readable, and it relieves the
reader of having to recall operator precedence from memory. Consider the following:
Python
Here the parentheses are fully unnecessary, as the comparison operators have higher precedence than and does and
would have been performed first anyhow. But some might consider the intent of the parenthesized version more
immediately obvious than this version without parentheses:
https://realpython.com/python-operators-expressions/ 15/22
6/28/2019 Operators and Expressions in Python – Real Python
On the other hand, there are probably those who would prefer the latter; it’s a matter of personal preference. The
point is, you can always use parentheses if you feel it makes the code more readable, even if they aren’t necessary to
change the order of evaluation.
Python
Improve Your Python>>>
...with a fresh 🐍 Python Trick 💌
code snippet every couple of days:
Email Address
>>> a = 10
>>> b = 20
>>> c = a * 5 + b Send Python Tricks »
>>> c
70
In fact, the expression to the right of the assignment can include references to the variable that is being assigned to:
Python >>>
>>> a = 10
>>> a = a + 5
>>> a
15
>>> b = 20
>>> b = b * 3
>>> b
60
The first example is interpreted as “a is assigned the current value of a plus 5,” e ectively increasing the value of a by
5. The second reads “b is assigned the current value of b times 3,” e ectively increasing the value of b threefold.
Of course, this sort of assignment only makes sense if the variable in question has already previously been assigned a
value:
Python >>>
>>> z = z / 12
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
z = z / 12
NameError: name 'z' is not defined
Python supports a shorthand augmented assignment notation for these arithmetic and bitwise operators:
Arithmetic Bitwise
+ &
- |
* ^
/ >>
% <<
//
**
Python
x <op>= y
x = x <op> y
Augmented Standard
Assignment Assignment
a += 5 is equivalent to Improve
a = a + 5 Your Python
Email Address
a /= 10 is equivalent to a = a / 10
Conclusion
In this tutorial, you learned about the diverse operators Python supports to combine objects into expressions.
Most of the examples you have seen so far have involved only simple atomic data, but you saw a brief introduction to
the string data type. The next tutorial will explore string objects in much more detail.
Take the Quiz: Test your knowledge with our interactive “Python Operators and Expressions” quiz. Upon
completion you will receive a score so you can track your learning progress over time:
🐍 Python Tricks 💌
Get a short & sweet Python Trick delivered to your inbox every couple of
days. No spam ever. Unsubscribe any time. Curated by the Real Python
team.
Email Address
https://realpython.com/python-operators-expressions/ 17/22
6/28/2019 Operators and Expressions in Python – Real Python
John is an avid Pythonista and a member of the Real Python tutorial team.
Email Address
Dan Joanna
Send Python Tricks »
Real Python Comment Policy: The most useful comments are those written with the goal of learning
from or helping out other readers—a er reading the whole article and all the earlier comments.
Complaints and insults generally won’t make the cut here.
LOG IN WITH
OR SIGN UP WITH DISQUS ?
Name
https://realpython.com/python-operators-expressions/ 18/22
6/28/2019 Operators and Expressions in Python – Real Python
why??
△ ▽ • Reply • Share ›
There are actually a few subtle things happening in your second expression.
First of all | is a binary bitwise OR- operator in regular Python, which is quite different from the logical OR-
operator in your first expression. For instance 1|2 = 3 because 1 is 01 in binary, 2 is 10 and doing bitwise OR
of 01 and 10 gives 11 which is the binary representation of 3.
Next, | has higher precedence than comparisons. This means that your second expression is evaluated
5 > (2|2) > 3
Improve Your Python
In contrast, or has lower precedence than comparisons so the first expression is evaluated as you would
expect:
(5>2) or (2>3) ...with a fresh 🐍 Python Trick 💌
Finally, because | binds so tight, the second expression is effectively
code snippet every couple of days:
5>2>3
(using that 2|2 = 2). This is what's called a chained comparison in Python. It is essentially
Email Address the same as having
an implicit AND operator between your comparisons:
(5>2) and (2>3)
see more
Send Python Tricks »
△ ▽ • Reply • Share ›
If x is not x is
“truthy” False
“falsy” True
But when evaluating as below, "not x" when x="falsy" evaluates to false. I would assume that to be the case because
values of x is a non empty string. It does not take into account that the string is "falsy"
⛺
△ ▽ • Reply • Share ›
The result of standard division (/) is always a float, even if the dividend is evenly divisible by the divisor:
>>> 10 / 5
2.0
>>> type(10 / 5)
<class 'float'="">
△ ▽ • Reply • Share ›
How to Get the Most Out of PyCon A Beginner’s Guide to the Python time Module
3 comments • 2 months ago 9 comments • 3 months ago
lalligood — In all of the articles I've read & podcasts I've Diego Andres Alvarez Marin — Correction: DO NOT take
Avatarlistened to, not a single one has ever mentioned Avatarinto account the leap seconds.
Guidebook. This …
How to Make a Twitter Bot in Python With Tweepy Python KeyError Exceptions and How to Handle
17 comments • 24 days ago Them
Mayank — Please elaborate "Why you want to use tweepy 9 comments • 3 months ago
AvatarAPI??"ex:I am planning to make twitter bot for auto … Chad G. Hansen — That is another great suggestion. I
Avatarpersonally haven't used it very much, but it can be very
useful in …
✉ Subscribe d Add Disqus to your siteAdd DisqusAdd 🔒 Disqus' Privacy PolicyPrivacy PolicyPrivacy
Keep Learning
🐍 Python Tricks 💌
https://realpython.com/python-operators-expressions/ 20/22
6/28/2019 Operators and Expressions in Python – Real Python
Email…
Table of Contents
Arithmetic Operators
Comparison Operators
Logical Operators
Bitwise Operators
Identity Operators
Operator Precedence
Augmented Assignment Operators
Conclusion
https://realpython.com/python-operators-expressions/ 21/22
6/28/2019 Operators and Expressions in Python – Real Python
Email Address
https://realpython.com/python-operators-expressions/ 22/22