Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
85 views

Operators and Expressions in Python Real Python

The document discusses various operators in Python and how they are used to create expressions by combining objects. It covers arithmetic, comparison, logical, bitwise and identity operators as well as operator precedence and augmented assignment operators.

Uploaded by

AnishaSapra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views

Operators and Expressions in Python Real Python

The document discusses various operators in Python and how they are used to create expressions by combining objects. It covers arithmetic, comparison, logical, bitwise and identity operators as well as operator precedence and augmented assignment operators.

Uploaded by

AnishaSapra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

6/28/2019 Operators and Expressions in Python – Real Python

Operators and Expressions in Python


by John Sturtz  12 Comments  basics 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:

Take the Quiz »


Improve Your Python

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

Improve Your Python


In this case, the + operator adds the operands a and b together. An operand can be either a literal value or a variable
that references an object:
...with a fresh 🐍 Python Trick 💌  
Python code snippet every couple of days:>>>

>>> 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:

Operator Example Meaning Result

+ (unary) +a Unary Positive a


In other words, it doesn’t really do anything. It mostly exists for
the sake of completeness, to complement Unary Negation.

+ (binary) a + b Addition Sum of a and b

- (unary) -a Unary Negation Value equal to a but opposite in sign

- (binary) a - b Subtraction b subtracted from a

* a * b Multiplication Product of a and b

/ a / b Division Quotient when a is divided by b.


The result always has type float.

% a % b Modulo Remainder when a is divided by b

// a // b Floor Division (also Quotient when a is divided by b, rounded to the next smallest
called Integer whole number
Division)

** a ** b Exponentiation a raised to the power of b

Here are some examples of these operators in use:

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

Improve Your Python


The result of standard division (/) is always a float, even if the dividend is evenly divisible by the divisor:
...with a fresh 🐍 Python Trick 💌  
Python code snippet every couple of days:>>>

>>> 10 / 5
2.0 Email Address
>>> type(10 / 5)
<class 'float'>

Send Python Tricks »


When the result of floor division (//) is positive, it is as though the fractional portion is truncated o , leaving only the
integer portion. When the result is negative, the result is rounded down to the next smallest (greater negative) integer:

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

== a == b Equal to True if the value of a is equal to the value of b


False otherwise

!= a != b Not equal to True if a is not equal to b


False otherwise
Improve Your Python

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 <= b Less than or equal to True if a is less than or equal to b


False otherwise

> a > b Greater than True if a is greater than b


False otherwise

>= a >= b Greater than or equal to True if a is greater than or equal to b


False otherwise
Improve Your Python
Here are examples of the comparison operators in use: ...with a fresh 🐍 Python Trick 💌  
code snippet every couple of days:
Python >>>

>>> a = 10 Email Address


>>> b = 20
>>> a == b
False
Send Python Tricks »
>>> a != b
True
>>> a <= b
True
>>> a >= b
False

>>> 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.

Equality Comparison on Floating-Point Values


Recall from the earlier discussion of floating-point numbers that the value stored internally for a float object may not
be precisely what you’d think it would be. For that reason, it is poor practice to compare floating-point values for
exact equality. Consider this example:

Python >>>

>>> x = 1.1 + 2.2


>>> x == 3.3
False

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 >>>

>>> tolerance = 0.00001


>>> x = 1.1 + 2.2
>>> abs(x - 3.3) < tolerance
True

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.

Logical Expressions Involving Boolean Operands


As you have seen, some objects and expressions in Python actually are of Boolean type. That is, they are equal to one
of the Python objects True or False. Consider these examples:

Python Improve Your Python>>>


>>> x = 5
...with a fresh 🐍 Python Trick 💌  
>>> x < 10
True
code snippet every couple of days:
>>> type(x < 10)
<class 'bool'> Email Address
>>> t = x > 10
>>> t
False Send Python Tricks »
>>> type(t)
<class 'bool'>

>>> 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:

Operator Example Meaning

not not x True if x is False


False if x is True
(Logically reverses the sense of x)

or x or y True if either x or y is True


False otherwise

and x and y True if both x and y are True


False otherwise

Take a look at how they work in practice below.

“not” and Boolean Operands


Python

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

Operand Value Logical Expression Value

x < 10 True not x < 10 False

callable(x) False not callable(x) True

“or” and Boolean Operands Improve Your Python


Python
...with a fresh 🐍 Python Trick 💌  
x = 5 code snippet every couple of days:
x < 10 or callable(x)
True
x < 0 or callable(x)
Email Address
False

Send Python Tricks »


Operand Value Operand Value Logical Expression Value

x < 10 True callable(x) False x < 10 or callable(x) True

x < 0 False callable(x) False x < 0 or callable(x) False

“and” and Boolean Operands


Python

x = 5
x < 10 and callable(x)
False
x < 10 and callable(len)
True

Operand Value Operand Value Logical Expression Value

x < 10 True callable(x) False x < 10 and callable(x) False

x < 10 True callable(len) True x < 10 or callable(len) True

Evaluation of Non-Boolean Values in Boolean Context


Many objects and expressions are not equal to True or False. Nonetheless, they may still be evaluated in Boolean
context and determined to be “truthy” or “falsy.”

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:

The Boolean value False


Any value that is numerically zero (0, 0.0, 0.0+0.0j)
An empty string
An object of a built-in composite data type which is empty (see below)
The special value denoted by the Python keyword None

Virtually any other object built into Python is regarded as true.


Improve Your Python
You can determine the “truthiness” of an object or expression with the built in b l() function b l() returns T if
https://realpython.com/python-operators-expressions/ 6/22
6/28/2019 Operators and Expressions in Python – Real Python
You can determine the “truthiness” of an object or expression with the built-in bool() function. bool() returns True if
its argument is truthy and False if it is falsy.

Numeric Value
A zero value is false.
A non-zero value is true.

Python >>>

>>> print(bool(0), bool(0.0), bool(0.0+0j))


False False False
Improve Your Python
>>> print(bool(-3), bool(3.14159), bool(1.0+1j))
True True True ...with a fresh 🐍 Python Trick 💌  
code snippet every couple of days:

String Email Address

An empty string is false.


A non-empty string is true. Send Python Tricks »

Python >>>

>>> print(bool(''), bool(""), bool(""""""))


False False False

>>> print(bool('foo'), bool(" "), bool(''' '''))


True True True

Built-In Composite Data Object


Python provides built-in composite data types called list, tuple, dict, and set. These are “container” types
that contain other objects. An object of one of these types is considered false if it is empty and true if it is non-
empty.

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

>>> type([1, 2, 3])


<class 'list'>
>>> bool([1, 2, 3])
True

The “None” Keyword


None is always false:

Python >>>

>>> bool(None)
False

Improve Your Python


Logical Expressions Involving Non-Boolean Operands
https://realpython.com/python-operators-expressions/ 7/22
6/28/2019
Logical Expressions Involving Non Boolean Operands
Operators and Expressions in Python – Real Python

Non-Boolean values can also be modified and joined by not, or and, and. The result depends on the “truthiness” of the
operands.

“not” and Non-Boolean Operands


Here is what happens for a non-Boolean value x:

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:

Python Email Address >>>

>>> x = 3
>>> bool(x)
True Send Python Tricks »
>>> not x
False

>>> x = 0.0
>>> bool(x)
False
>>> not x
True

“or” and Non-Boolean Operands


This is what happens for two non-Boolean values x and y:

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.

“and” and Non-Boolean Operands


Here’s what you’ll get for two non-Boolean values x and y:

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

Improve Your Python


>>> y = 4.4
>>> x and y
0.0
...with a fresh 🐍 Python Trick 💌  
code snippet every couple of days:
As with or, the expression x and y does not evaluate to either True or False, but instead to one of either x or y. x and y
will be truthy if both x and y are truthy, and falsy otherwise. Email Address

Compound Logical Expressions and Short-Circuit Evaluation


Send Python Tricks »
So far, you have seen expressions with only a single or or and operator and two operands:

Python

x or y
x and y

Multiple logical operators and operands can be strung together to form compound logical expressions.

Compound “or” Expressions


Consider the following expression:

x1 or x2 or x3 or … xn

This expression is true if any of the xi are true.

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:

f() takes a single argument.

It displays the argument to the console.


It returns the argument passed to it as its return value.

(You will see how to define such a function in the upcoming tutorial on Functions.)

Several example calls to f() are shown below:

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.

Now, consider the following compound logical expression:

Python >>>

>>> f(0) or f(False) or f(1) or f(2) or f(3)


-> f(0) = 0
-> f(False) = False
-> f(1) = 1
Improve Your Python
1
...with a fresh 🐍 Python Trick 💌  
code snippet every couple of days:
The interpreter first evaluates f(0), which is 0. A numeric value of 0 is false. The expression is not true yet, so
evaluation proceeds le to right. The next operand, f(False), returns False. That is Email
also Address
false, so evaluation
continues.

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.

Compound “and” Expressions


A similar situation exists in an expression with multiple and operators:

x1 and x2 and x3 and … xn

This expression is true if all the xi are true.

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 >>>

>>> f(1) and f(False) and f(2) and f(3)


-> f(1) = 1
-> f(False) = False
False

>>> f(1) and f(0.0) and f(2) and f(3)


-> f(1) = 1
-> f(0.0) = 0.0
0.0

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 >>>

>>> f(1) and f(2.2) and f('bar')


-> f(1) = 1
-> f(2.2) = 2.2
-> f(bar) = bar
'bar'

Improve Your Python

https://realpython.com/python-operators-expressions/ 10/22
6/28/2019 Operators and Expressions in Python – Real Python

Idioms That Exploit Short-Circuit Evaluation


There are some common idiomatic patterns that exploit short-circuit evaluation for conciseness of expression.

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:

Python Email Address >>>

>>> 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

You can avoid an error with an expression like this:

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

Selecting a Default Value


Another idiom involves selecting a default value when a specified value is zero or empty. For example, suppose you
want to assign a variable s to the value contained in another variable called string. But if string is empty, you want to
supply a default value.

Here is a concise way of expressing this using short-circuit evaluation:

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 >>>

>>> string = 'foo bar'


>>> s = string or '<default_value>'
>>> s
'foo bar'

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 >>>

>>> string = '' Improve Your Python


>>> s = string or '<default_value>'
>>> s ...with a fresh 🐍 Python Trick 💌  
'<default_value>' code snippet every couple of days:

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

x < f() <= z


x < f() and f() <= z

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:

x1 op1 x2 op2 x3 … xn-1 opn xn

x1 op1 x2 and x2 op2 x3 and … xn-1 opn xn

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:

Operator Example Meaning Result

& 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)

Improve Your Python


>> a >> n Shi right Each bit is shi ed right n places.
n places ...with a fresh 🐍 Python Trick 💌  
code snippet every couple of days:
<< a << n Shi le n Each bit is shi ed le n places.
places Email Address

Here are some examples:


Send Python Tricks »
Python >>>

>>> '0b{:04b}'.format(0b1100 & 0b1010)


'0b1000'
>>> '0b{:04b}'.format(0b1100 | 0b1010)
'0b1110'
>>> '0b{:04b}'.format(0b1100 ^ 0b1010)
'0b0110'
>>> '0b{:04b}'.format(0b1100 >> 2)
'0b0011'
>>> '0b{:04b}'.format(0b0011 << 2)
'0b1100'

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

x and y do not have the same identity, and x is y returns False.

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.

Unsurprisingly, the opposite of is is is not:

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

lowest precedence or Boolean OR

and Boolean AND

not Boolean
Improve NOT
Your Python

https://realpython.com/python-operators-expressions/ 14/22
6/28/2019 Operators and Expressions in Python – Real Python

  , !=, <, <=, >, >=, is, is not


Operator
== comparisons,
Description identity

| bitwise OR

^ bitwise XOR

& bitwise AND

<<, >> bit shi s

+, - 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

Send Python Tricks »


Operators at the top of the table have the lowest precedence, and those at the bottom of the table have the highest.
Any operators in the same row of the table have equal precedence.

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

(a < 10) and (b > 30)

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:

Python Improve Your Python

https://realpython.com/python-operators-expressions/ 15/22
6/28/2019 Operators and Expressions in Python – Real Python

a < 10 and b > 30

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.

Augmented Assignment Operators


You have seen that a single equal sign (=) is used to assign a value to a variable. It is, of course, perfectly viable for the
value to the right of the assignment to be an expression containing other variables:

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

+ &
- |
* ^
/ >>
% <<
//
**

Improve Your Python


For these operators, the following are equivalent:
https://realpython.com/python-operators-expressions/ 16/22
6/28/2019 Operators and Expressions in Python – Real Python

Python

x <op>= y
x = x <op> y

Take a look at these examples:

Augmented Standard
Assignment Assignment

a += 5 is equivalent to Improve
a = a + 5 Your Python

...with a fresh 🐍 Python Trick 💌  


code snippet every couple of days:

Email Address

a /= 10 is equivalent to a = a / 10

Send Python Tricks »


a ^= b is equivalent to a = a ^ b

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:

Take the Quiz »

« Variables in Python Operators and Expressions in Strings in Python »


Python

🐍 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

Send Me Python Tricks »

Improve Your Python

https://realpython.com/python-operators-expressions/ 17/22
6/28/2019 Operators and Expressions in Python – Real Python

About John Sturtz

John is an avid Pythonista and a member of the Real Python tutorial team.

» More about John

Improve Your Python


Each tutorial at Real Python is created by a team of developers so that it meets...with a fresh
our high 🐍 Python Trick 💌
quality   members who
standards. The team
worked on this tutorial are: code snippet every couple of days:

Email Address

Dan Joanna
Send Python Tricks »

What Do You Think?

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.

11 Comments Real Python 


1 Login

 Recommend 1 t Tweet f Share Sort by Best

Join the discussion…

LOG IN WITH
OR SIGN UP WITH DISQUS ?

Name

Chanchal • 3 days ago


Is there an error in the example provided in the following section?
Sub-heading: “and” and Boolean Operands
line: x < 10 True callable(len) True x < 10 or callable(len) True
error: shouldn't this be written as True x < 10 and callable(len) True
?
First one is also right, but not what i would expect in an example for " "and" and boolean"
△ ▽ • Reply • Share ›

bruce • 18 days ago


>>> 5>2 or 2>3
True
>>>5>2 | 2>3
False Improve Your Python

https://realpython.com/python-operators-expressions/ 18/22
6/28/2019 Operators and Expressions in Python – Real Python

why??
△ ▽ • Reply • Share ›

Geir Arne Hjelle > bruce • 18 days ago


Hi Bruce.

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 ›

Vivek Vyas • 23 days ago


Tutorial states:

“not” and Non-Boolean Operands


Here is what happens for a non-Boolean value x:

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 ›

Vivek Vyas > Vivek Vyas • 23 days ago


never mind. it appeared that the tutorial was talking about a variable value "falsy" but it seems it is talking
about the variable evaluating to falsy. Just a suggestion
- Would help new reader if made more clear
△ ▽ • Reply • Share ›

Vivek Vyas • 23 days ago • edited


Does not seem like result of standard division is always float. See attached.

Based on this, Is the following, as stated in the tutorial correct?

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 ›

Yuntai Kyong • 5 months ago


I happened to come across this usage
[1,2,3] * False == []
How do you think it should be explained?
△ ▽ • Reply • Share ›
Improve Your Python
Sunil Sikka > Yuntai Kyong • 3 months ago
https://realpython.com/python-operators-expressions/ 19/22
6/28/2019 Operators and Expressions in Python – Real Python
Sunil Sikka > Yuntai Kyong • 3 months ago
False is equivalent to 0 in * therefor
[1,2,3]*False is
[1,2,3]*0
=[]
because multiplying any list by 0 is []
△ ▽ • Reply • Share ›

Yuntai Kyong > Sunil Sikka • 5 days ago


ah.. thanks!
△ ▽ • Reply • Share ›

Show more replies

dimrok • a year ago Improve Your Python


Good tutorial.
...with a fresh 🐍 Python Trick 💌  
By the way, some snippets are missing `>>>` making them a bit confusing, e.g. `or`, `not` and `and` operators.
code snippet every couple of days:
△ ▽ • Reply • Share ›

tongzilv • a year ago Email Address


Good tutorial,Thank you
△ ▽ • Reply • Share ›
Send Python Tricks »
ALSO ON REAL PYTHON

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

Related Tutorial Categories: basics python

— FREE Email Series —

🐍 Python Tricks 💌

Improve Your Python

https://realpython.com/python-operators-expressions/ 20/22
6/28/2019 Operators and Expressions in Python – Real Python

Email…

Get Python Tricks »


Improve Your Python
🔒 No spam. Unsubscribe any time. ...with a fresh 🐍 Python Trick 💌  
code snippet every couple of days:

All Tutorial Topics Email Address


advanced api basics best-practices community databases data-science

devops django docker flask front-end intermediate machine-learning


Send Python Tricks »
python testing tools web-dev web-scraping

Table of Contents
Arithmetic Operators
Comparison Operators
Logical Operators
Bitwise Operators
Identity Operators
Operator Precedence
Augmented Assignment Operators
Conclusion

Improve Your Python

https://realpython.com/python-operators-expressions/ 21/22
6/28/2019 Operators and Expressions in Python – Real Python

© 2012–2019 Real Python ⋅ Newsletter ⋅ YouTube ⋅ Twitter ⋅ Facebook ⋅ Instagram


Python Tutorials ⋅ Search ⋅ Privacy Policy ⋅ Advertise ⋅ Contact
❤ Happy Pythoning!

Improve Your Python


...with a fresh 🐍 Python Trick 💌  
code snippet every couple of days:

Email Address

Send Python Tricks »

Improve Your Python

https://realpython.com/python-operators-expressions/ 22/22

You might also like