Easy Tutorial
❮ Python String Translate Python Func Dict ❯

Python3 Operators


What are Operators?

This section primarily explains the operators in Python.

Here is a simple example:

4 + 5 = 9

In this example, 4 and 5 are called operands, and + is called the operator.

Python language supports the following types of operators:

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


Python Arithmetic Operators

Assume variable a=10 and variable b=21:

Operator Description Example
+ Addition - Adds two objects a + b outputs 31
- Subtraction - Gets negative number or subtracts one number from another a - b outputs -11
* Multiplication - Multiplies two numbers or returns a repeated string a * b outputs 210
/ Division - x divided by y b / a outputs 2.1
% Modulus - Returns the remainder of 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 - The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity) >>> 9//2<br>4<br>>>> -9//2<br>-5

The following example demonstrates all arithmetic operations in Python:

Example (Python 3.0+)

#!/usr/bin/python3

a = 21
b = 10
c = 0

c = a + b
print("1 - c 的值为:", c)

c = a - b
print("2 - c 的值为:", c)

c = a * b
print("3 - c 的值为:", c)

c = a / b
print("4 - c 的值为:", c)

c = a % b
print("5 - c 的值为:", c)

# Modify variables a, b, c
a = 2
b = 3
c = a**b 
print("6 - c 的值为:", c)

a = 10
b = 5
c = a//b 
print("7 - c 的值为:", c)

The output of the above example is:

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:

Operator Description Example
== Equal - Compares if objects are equal (a == b) returns False.
!= Not Equal - Compares if two objects are not equal (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. This is equivalent to the special variables True and False respectively. Note that these variable names are capitalized. (a < b) returns True.
>= Greater Than or Equal To - Returns whether x is greater than or equal to y. (a >= b) returns False.
<= Less Than or Equal To - Returns whether x is less than or equal to y. (a <= b) returns True.

The following example demonstrates all comparison operations in Python:

Example (Python 3.0+)

#!/usr/bin/python3

a = 21
b = 10
c = 0

if ( a == b ):
   print("1 - a 等于 b")
else:
   print("1 - a 不等于 b")

if ( a != b ):
   print("2 - a 不等于 b")
else:
   print("2 - a 等于 b")

if ( a < b ):
   print("3 - a 小于 b")
else:
   print("3 - a 大于等于 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")

Python Assignment Operators

Assume variable a holds 10 and variable b holds 20, then:

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
%= Modulus assignment operator c %= a is equivalent to c = c % a
**= Exponentiation assignment operator c *= a is equivalent to c = c * a
//= Floor division assignment operator c //= a is equivalent to c = c // a
:= Walrus operator, which allows assignment of variables within an expression. Added in Python 3.8. In this example, the assignment expression avoids calling len() twice: if (n := len(a)) > 10: <br> print(f"List is too long ({n} elements, expected <= 10)")

The following example demonstrates all assignment operators in Python:

Example (Python 3.0+)

#!/usr/bin/python3

a = 21
b = 10
c = 0

c = a + b
print("1 - c is:", c)

c += a
print("2 - c is:", c)

c *= a
print("3 - c is:", c)

c /= a
print("4 - c is:", c)

c = 2
c %= a
print("5 - c is:", c)

c **= a
print("6 - c is:", c)

c //= a
print("7 - c is:", c)

Output:

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

Python Bitwise Operators

Bitwise operators treat numbers as binary and perform operations accordingly. The rules for bitwise operations in Python are as follows:

Assume variable a is 60 and variable b is 13 in binary format:

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 operator: If both bits are 1, the result is 1, otherwise 0 (a & b) outputs 12, binary: 0000 1100
| Bitwise OR operator: If at least one bit is 1, the result is 1 (a | b) outputs 61, binary: 0011 1101
^ Bitwise XOR operator: If the bits are different, the result is 1 (a ^ b) outputs 49, binary: 0011 0001
~ Bitwise NOT operator: Flips all bits, 1 to 0 and 0 to 1. ~x is similar to -x-1 (~a) outputs -61, binary: 1100 0011, in two's complement form
<< Left shift operator: Shifts bits to the left by the number specified on the right, filling with 0s a << 2 outputs 240, binary: 1111 0000

Right Shift Operator: The ">>" shifts all bits of the left operand to the right by a number of positions specified by the right operand. For example, a >> 2 outputs 15, with a binary interpretation of 0000 1111.

The following example demonstrates the operations of all bitwise operators in Python:

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 - c 的值为:", c)

c = a | b        # 61 = 0011 1101 
print ("2 - c 的值为:", c)

c = a ^ b        # 49 = 0011 0001
print ("3 - c 的值为:", c)

c = ~a           # -61 = 1100 0011
print ("4 - c 的值为:", c)

c = a << 2       # 240 = 1111 0000
print ("5 - c 的值为:", c)

c = a >> 2       # 15 = 0000 1111
print ("6 - c 的值为:", c)

The output of the above example:

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. The following assumes variable a is 10 and b is 20:

Operator Logical Expression Description Example
and x and y Boolean "AND" - If x is False, it returns the value of x, otherwise it returns the evaluated 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 evaluated value of y. (a or b) returns 10.
not not x Boolean "NOT" - If x is True, it returns False. If x is False, it returns True. not(a and b) returns False

The output of the above example:

Example (Python 3.0+)

#!/usr/bin/python3

a = 10
b = 20

if ( a and b ):
   print ("1 - 变量 a 和 b 都为 true")
else:
   print ("1 - 变量 a 和 b 有一个不为 true")

if ( a or b ):
   print ("2 - 变量 a 和 b 都为 true,或其中一个变量为 true")
else:
   print ("2 - 变量 a 和 b 都不为 true")

# Modify the value of a
a = 0
if ( a and b ):
   print ("3 - 变量 a 和 b 都为 true")
else:
   print ("3 - 变量 a 和 b 有一个不为 true")

if ( a or b ):
   print ("4 - 变量 a 和 b 都为 true,或其中一个变量为 true")
else:
   print ("4 - 变量 a 和 b 都不为 true")

if not( a and b ):
   print ("5 - 变量 a 和 b 都为 false,或其中一个变量为 false")
else:
   print ("5 - 变量 a 和 b 都为 true")

The output of the above example:

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 above operators, Python also supports membership operators, which test for membership in a sequence, such as strings, lists, or tuples.

Operator Description Example
in Returns True if a value is found in the specified sequence, otherwise False. x in y, returns True if x is found in the sequence y.

This is a Chinese to English translation. Please provide the English translation for this text without providing any explanations or text apart from the translation.

Chinese: | not in | Returns True if the value is not found in the specified sequence, otherwise returns False. | x is not in y sequence, returns True if x is not in y sequence. |

The following example demonstrates the operation of all membership operators in Python:

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 found in the given list")
else:
   print ("1 - Variable a is not found in the given list")

if ( b not in list ):
   print ("2 - Variable b is not found in the given list")
else:
   print ("2 - Variable b is found in the given list")

# Modify the value of a
a = 2
if ( a in list ):
   print ("3 - Variable a is found in the given list")
else:
   print ("3 - Variable a is not found in the given list")

The output of the above example is:

1 - Variable a is not found in the given list
2 - Variable b is not found in the given list
3 - Variable a is found in the given list

Python Identity Operators

Identity operators are used to compare the memory locations of two objects.

Operator Description Example
is is checks if both identifiers refer to the same object x is y, similar to id(x) == id(y), returns True if both refer to the same object, otherwise returns False
is not is not checks if both identifiers refer to different objects x is not y, similar to id(x) != id(y), returns True if both refer to different objects, otherwise returns False

Note: The id() function is used to get the memory address of the object.

The following example demonstrates the operation of all identity operators in Python:

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 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 output of the above example is:

1 - a and b have the same identity
2 - a and b have the same identity
3 - a and b do not have the same identity
4 - a and b do not have the same identity

>

Difference between is and ==:

is is used to check if two variables refer to the same object, while == is used to check if the values of the 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 following table lists all operators from highest to lowest precedence. Operators in the same cell have the same precedence. All operators refer to binary operations unless specified otherwise. Operators in the same cell are grouped from left to right (except for exponentiation which is grouped from right to left):

Operator Description
(expressions...), [expressions...],<br> {key: value...},<br> {expressions...} Parenthetical expressions
x[index], x[index:index],<br> x(arguments...), x.attribute Subscription, slicing, calling, attribute reference
await x await expression
** Exponentiation
+x, -x, ~x Positive, negative, bitwise NOT
*, @, /, //, % Multiplication, matrix multiplication, division, floor division, remainder
+, - Addition and subtraction

This is a Chinese to English translation, please provide the English translation for this text. Do not provide any explanations or text apart from the translation. Chinese: | <<, >> | Shift | | & | Bitwise AND | | ^ | Bitwise XOR | | | | Bitwise OR | | in,not in,<br> is,is not, <,<br> <=, >, >=, !=, == | Comparison operators, including membership 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 the operation of all 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 result is:",  e)

e = ((a + b) * c) / d     # (30 * 15 ) / 5
print ("((a + b) * c) / d result is:",  e)

e = (a + b) * (c / d)    # (30) * (15/5)
print ("(a + b) * (c / d) result is:",  e)

e = a + (b * c) / d      #  20 + (150/5)
print ("a + (b * c) / d result is:",  e)

The output of the above example is:

(a + b) * c / d result is: 90.0
((a + b) * c) / d result is: 90.0
(a + b) * (c / d) result is: 90.0
a + (b * c) / d result is: 50.0

and has higher precedence:

Example

x = True
y = False
z = False

if x or y and z:
    print("yes")
else:
    print("no")

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

yes

Note: The <> operator is no longer supported in Python 3. You can use != instead. If you must use this comparison operator, you can do so as follows:

>>> from __future__ import barry_as_FLUFL
>>> 1 <> 2
True

x = True
y = False
z = False

if x or y and z:
    print("yes")
else:
    print("no")
x = True
y = False
z = False

if not x or y:
    print(1)
elif not x or not y and z:
    print(2)
elif not x or y or not y and x:
    print(3)
else:
    print(4)

Practice Exercises

❮ Python String Translate Python Func Dict ❯