Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 Operators

Python3 Operators


What is an operator?

This chapter mainly explains Python's operators.

Take a simple example:

4 + 5 = 9

In the example,4 and 5 are calledoperands, and + is called theoperator。

The Python language supports the following types of operators:

Next let's learn Python's operators one by one.


Python arithmetic operators

Assume variable a=10 and variable b=21 below:

operator Description Example
+ Add - adds two objects together a + b outputs 31
- Subtract - yields a negative number or subtracts one number from another a - b outputs -11
* Multiply - multiplies two numbers or returns a string repeated several times a * b outputs 210
/ Divide - x divided by y b / a outputs 2.1
% Modulo - returns the remainder of a division b % a outputs 1
** Exponent - returns x raised to the power of y a**b is 10 to the power of 21
// Floor division - rounds down to an integer
>>> 9//2

4 >>> -9//2 -5 |

The following example demonstrates all of Python's arithmetic operators:

Example (Python 3.0+)

#!/usr/bin/python3

a

=

21

b

=

10

c

=

0

c

=

a

b

print

(

"

1 - the value of c is:

"

,

c

)

c

=

a

b

print

(

"

2 - the value of c is:

"

,

c

)

c

=

a

b

print

(

"

3 - the value of c is:

"

,

c

)

c

=

a

/

b

print

(

"

4 - the value of c is:

"

,

c

)

c

=

a

%

b

print

(

"

5 - the value of c is:

"

,

c

)

Modify variables a, b, and c

a

=

2

b

=

3

c

=

a

**

b

print

(

"

6 - the value of c is:

"

,

c

)

a

=

10

b

=

5

c

=

a

//

b

print

(

"

7 - the value of c is:

"

,

c

)

The example above produces the following output:


1 - c 的值为: 31
2 - c 的值为: 11
3 - c 的值为: 210
4 - c 的值为: 2.1
5 - c 的值为: 1
6 - c 的值为: 8
7 - c 的值为: 2

Python comparison operators

Assume variable a is 10 and variable b is 20 below:

operator Description Example
== Equal - checks whether objects are equal (a == b) returns False.
!= Not equal - checks whether two objects are different (a != b) returns True.
> Greater than - returns whether x is greater than y (a > b) returns False.
< Less than - returns whether x is less than y. All comparison operators return 1 for true and 0 for false, which are equivalent to the special variables True and False. Note the capitalization of these variable names. (a < b) returns True.
>= Greater than or equal - returns whether x is greater than or equal to y. (a >= b) returns False.
<= Less than or equal - returns whether x is less than or equal to y. (a <= b) returns True.

The following example demonstrates all of Python's comparison operators:

Example (Python 3.0+)

#!/usr/bin/python3

a

=

21

b

=

10

c

=

0

if

(

a

==

b

)

:

print

(

"

1 - a equals b

"

)

else

:

print

(

"

1 - a does not equal b

"

)

if

(

a

!=

b

)

:

print

(

"

2 - a does not equal b

"

)

else

:

print

(

"

2 - a equals b

"

)

if

(

a

<

b

)

:

print

(

"

3 - a is less than b

"

)

else

:

print

(

"

3 - a is greater than or equal to b

"

)

if

(

a

b

)

:

print

(

"

4 - a is greater than b

"

)

else

:

print

(

"

4 - a is less than or equal to b

"

)

Modify the values of variables a and b

a

=

5

b

=

20

if

(

a

<=

b

)

:

print

(

"

5 - a is less than or equal to b

"

)

else

:

print

(

"

5 - a is greater than b

"

)

if

(

b

=

a

)

:

print

(

"

6 - b is greater than or equal to a

"

)

else

:

print

(

"

6 - b is less than a

"

)

The example above produces the following output:


1 - a 不等于 b
2 - a 不等于 b
3 - a 大于等于 b
4 - a 大于 b
5 - a 小于等于 b
6 - b 大于等于 a

Python assignment operators

Assume variable a is 10 and variable b is 20 below:

operator Description Example
= Simple assignment operator c = a + b assigns the result of a + b to c
+= Addition assignment operator c += a is equivalent to c = c + a
-= Subtraction assignment operator c -= a is equivalent to c = c - a
*= Multiplication assignment operator c *= a is equivalent to c = c * a
/= Division assignment operator c /= a is equivalent to c = c / a
%= Modulo assignment operator c %= a is equivalent to c = c % a
**= Exponent assignment operator c **= a is equivalent to c = c ** a
//= Floor division assignment operator c //= a is equivalent to c = c // a
:= Walrus operator; its main purpose is to assign a value and return that value within an expression at the same time.Operator added in Python 3.8。

In this example, the assignment expression avoids calling len() twice:

if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)")

The following example demonstrates all of Python's assignment operators:

Example (Python 3.0+)

#!/usr/bin/python3

a

=

21

b

=

10

c

=

0

c

=

a

b

print

(

"

1 - the value of c is:

"

,

c

)

c

+=

a

print

(

"

2 - the value of c is:

"

,

c

)

c

*=

a

print

(

"

3 - the value of c is:

"

,

c

)

c

/=

a

print

(

"

4 - the value of c is:

"

,

c

)

c

=

2

c

%=

a

print

(

"

5 - the value of c is:

"

,

c

)

c

**=

a

print

(

"

6 - the value of c is:

"

,

c

)

c

//=

a

print

(

"

7 - the value of c is:

"

,

c

)

The example above produces the following output:


1 - c 的值为: 31
2 - c 的值为: 52
3 - c 的值为: 1092
4 - c 的值为: 52.0
5 - c 的值为: 2
6 - c 的值为: 2097152
7 - c 的值为: 99864

In Python 3.8 and later, a new syntax feature called the "walrus operator" was introduced, using the := symbol. Its main purpose is to assign a value and return that value within an expression at the same time.

Using the walrus operator can simplify code in some cases, especially when the assignment result is needed inside an expression. This is useful for simplifying loop conditions or repeated computations in expressions.

Below is a simple example demonstrating the use of the walrus operator:

Example

Traditional approach

n

=

10

if

n

5

:

   

print

(

n

)

Use the walrus operator

if

(

n :

=

10

)

5

:

   

print

(

n

)

- `(n := 10)`: assigns 10 to variable `n` and returns that assignment result. - `> 5`: checks whether the assigned `n` is greater than 5. If the condition is true, the following code block is executed.

Advantages of the walrus operator:


Python bitwise operators

Bitwise operators treat numbers as binary. Python's bitwise operator rules are as follows:

In the table below, variable a is 60 and b is 13; their binary formats are as follows:


a = 0011 1100

b = 0000 1101

-----------------

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a  = 1100 0011
operator Description Example
& Bitwise AND: for two values, if both corresponding bits are 1 the resulting bit is 1, otherwise 0 (a & b) outputs 12, binary: 0000 1100
| Bitwise OR: if either of the two corresponding bits is 1, the resulting bit is 1. (a | b) outputs 61, binary: 0011 1101
^ Bitwise XOR: when the two corresponding bits differ, the result is 1 (a ^ b) outputs 49, binary: 0011 0001
~ Bitwise NOT: inverts each binary bit, turning 1 into 0 and 0 into 1. ~x is similar to -x-1 (~a ) outputs -61, binary: 1100 0011, in the two's complement form of a signed binary number.
<< Left shift operator: all binary bits of the operand are shifted left by the number of positions specified by the value on the right of "<<"; high-order bits are discarded and low-order bits are filled with 0. a << 2 outputs 240, binary: 1111 0000
>> Right shift operator: all binary bits of the operand on the left of ">>" are shifted right by the number of positions specified by the value on the right of ">>" a >> 2 outputs 15, binary: 0000 1111

The following example demonstrates all of Python's bitwise operators:

Example (Python 3.0+)

#!/usr/bin/python3

a

=

60

60 = 0011 1100

b

=

13

13 = 0000 1101

c

=

0

c

=

a

&

b

12 = 0000 1100

print

(

"

1 - the value of c is:

"

,

c

)

c

=

a

|

b

61 = 0011 1101

print

(

"

2 - the value of c is:

"

,

c

)

c

=

a

^

b

49 = 0011 0001

print

(

"

3 - the value of c is:

"

,

c

)

c

= ~

a

-61 = 1100 0011

print

(

"

4 - the value of c is:

"

,

c

)

c

=

a

<<

2

240 = 1111 0000

print

(

"

5 - the value of c is:

"

,

c

)

c

=

a

2

15 = 0000 1111

print

(

"

6 - the value of c is:

"

,

c

)

The example above produces the following output:


1 - c 的值为: 12
2 - c 的值为: 61
3 - c 的值为: 49
4 - c 的值为: -61
5 - c 的值为: 240
6 - c 的值为: 15

Python logical operators

Python supports logical operators; assume variable a is 10 and b is 20 below:

operator Logical expression Description Example
and x and y Boolean "and" - if x is False, x and y returns the value of x, otherwise it returns the computed value of y. (a and b) returns 20.
or x or y Boolean "or" - if x is True, it returns the value of x, otherwise it returns the computed value of y. (a or b) returns 10.
not not x Boolean "not" - if x is True, returns False; if x is False, returns True. not(a and b) returns False

The example above produces the following output:

Example (Python 3.0+)

#!/usr/bin/python3

a

=

10

b

=

20

if

(

a

and

b

)

:

print

(

"

1 - variables a and b are both true

"

)

else

:

print

(

"

1 - one of variables a and b is not true

"

)

if

(

a

or

b

)

:

print

(

"

2 - variables a and b are both true, or one of them is true

"

)

else

:

print

(

"

2 - neither variable a nor b is true

"

)

Modify the value of variable a

a

=

0

if

(

a

and

b

)

:

print

(

"

3 - variables a and b are both true

"

)

else

:

print

(

"

3 - one of variables a and b is not true

"

)

if

(

a

or

b

)

:

print

(

"

4 - variables a and b are both true, or one of them is true

"

)

else

:

print

(

"

4 - neither variable a nor b is true

"

)

if

not

(

a

and

b

)

:

print

(

"

5 - variables a and b are both false, or one of them is false

"

)

else

:

print

(

"

5 - variables a and b are both true

"

)

The example above produces the following output:


1 - 变量 a 和 b 都为 true
2 - 变量 a 和 b 都为 true,或其中一个变量为 true
3 - 变量 a 和 b 有一个不为 true
4 - 变量 a 和 b 都为 true,或其中一个变量为 true
5 - 变量 a 和 b 都为 false,或其中一个变量为 false

Python membership operators

In addition to the operators above, Python also supports membership operators, which test whether a sequence contains members, including strings, lists, or tuples.

operator Description Example
in Returns True if the value is found in the specified sequence, otherwise False. x is in sequence y; returns True if x is in sequence y.
not in Returns True if the value is not found in the specified sequence, otherwise False. x is not in sequence y; returns True if x is not in sequence y.

The following example demonstrates all of Python's membership operators:

Example (Python 3.0+)

#!/usr/bin/python3

a

=

10

b

=

20

list

=

[

1

,

2

,

3

,

4

,

5

]

if

(

a

in

list

)

:

print

(

"

1 - variable a is in the given list

"

)

else

:

print

(

"

1 - variable a is not in the given list

"

)

if

(

b

not

in

list

)

:

print

(

"

2 - variable b is not in the given list

"

)

else

:

print

(

"

2 - variable b is in the given list

"

)

Modify the value of variable a

a

=

2

if

(

a

in

list

)

:

print

(

"

3 - variable a is in the given list

"

)

else

:

print

(

"

3 - variable a is not in the given list

"

)

The example above produces the following output:


1 - 变量 a 不在给定的列表中 list 中
2 - 变量 b 不在给定的列表中 list 中
3 - 变量 a 在给定的列表中 list 中

Python identity operators

Identity operators compare the memory locations of two objects

operator Description Example
is is checks whether two identifiers refer to the same object x is y, similar to id(x) == id(y) , returns True if they reference the same object, otherwise False
is not is not checks whether two identifiers refer to different objects ** x is not y** , similar to id(x) != id(y). Returns True if they do not reference the same object, otherwise False.

Note: id() The function is used to get an object's memory address.

The following example demonstrates all of Python's identity operators:

Example (Python 3.0+)

#!/usr/bin/python3

a

=

20

b

=

20

if

(

a

is

b

)

:

print

(

"

1 - a and b have the same identity

"

)

else

:

print

(

"

1 - a and b do not have the same identity

"

)

if

(

id

(

a

)

==

id

(

b

)

)

:

print

(

"

2 - a and b have the same identity

"

)

else

:

print

(

"

2 - a and b do not have the same identity

"

)

Modify the value of variable b

b

=

30

if

(

a

is

b

)

:

print

(

"

3 - a and b have the same identity

"

)

else

:

print

(

"

3 - a and b do not have the same identity

"

)

if

(

a

is

not

b

)

:

print

(

"

4 - a and b do not have the same identity

"

)

else

:

print

(

"

4 - a and b have the same identity

"

)

The example above produces the following output:


1 - a 和 b 有相同的标识
2 - a 和 b 有相同的标识
3 - a 和 b 没有相同的标识
4 - a 和 b 没有相同的标识

Difference between is and ==:

is checks whether two variables reference the same object, while == checks whether the values of the referenced variables are equal.

>>>a = [1, 2, 3] >>> b = a >>> b is a True >>> b == a True >>> b = a[:] >>> b is a False >>> b == a True

Python operator precedence

The table below lists all operators from highest to lowest precedence. Operators in the same cell have the same precedence. Operators refer to binary operations unless stated otherwise. Operators in the same cell group left to right (except exponentiation, which groups right to left):

operator

Description

(expressions...),

[expressions...], {key: value...}, {expressions...}

Parenthesized expressions

x[index], x[index:index], x(arguments...), x.attribute

Subscription, slicing, call, attribute reference

await x

await expression

**

Exponentiation

+x, -x, ~x

Unary plus, minus, bitwise NOT

*, @, /, //, %

Multiplication, matrix multiplication, division, floor division, remainder

+, -

Addition and subtraction

<<, >>

Shift

&

Bitwise AND

^

Bitwise XOR

|

Bitwise OR

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

Comparisons, including membership tests and identity tests

not x

Logical NOT

and

Logical AND

or

Logical OR

if -- else

Conditional expression

lambda

lambda expression

:=

Assignment expression

The following example demonstrates operator precedence in Python:

Example (Python 3.0+)

#!/usr/bin/python3

a

=

20

b

=

10

c

=

15

d

=

5

e

=

0

e

=

(

a

b

)

c

/

d

#( 30 * 15 ) / 5

print

(

"

(a + b) * c / d evaluates to:

"

,

e

)

e

=

(

(

a

b

)

c

)

/

d

(30 * 15 ) / 5

print

(

"

((a + b) * c) / d evaluates to:

"

,

e

)

e

=

(

a

b

)

(

c

/

d

)

(30) * (15/5)

print

(

"

(a + b) * (c / d) evaluates to:

"

,

e

)

e

=

a

(

b

c

)

/

d

20 + (150/5)

print

(

"

a + (b * c) / d evaluates to:

"

,

e

)

The example above produces the following output:


(a + b) * c / d 运算结果为: 90.0
((a + b) * c) / d 运算结果为: 90.0
(a + b) * (c / d) 运算结果为: 90.0
a + (b * c) / d 运算结果为: 50.0

and has higher precedence:

Example

x

=

True

y

=

False

z

=

False

print

(

"

Case 1: default precedence (and is evaluated first)

"

)

if

x

or

y

and

z

:

Equivalent to x or (y and z)

print

(

"

yes

"

)

Will output

else

:

print

(

"

no

"

)

print

(

"

\n

Case 2: force a different precedence (or is evaluated first)

"

)

if

(

x

or

y

)

and

z

:

Add parentheses manually to change the order

print

(

"

yes

"

)

Will not output

else

:

print

(

"

no

"

)

Will output

In the example above, y and z is evaluated first and returns False, then x or False returns True, giving the output:

情况1:默认优先级(先算and)
yes

情况2:强制改变优先级(先算or)
no

Note:Python3 no longer supports the <> operator; you can use != instead. If you must use this kind of comparison operator, you can use the following approach:

>>> from __future__ import barry_as_FLUFL

>>> 1 <> 2 True