Python Operators


What is an Operator?

This chapter mainly explains Python operators. Let's take a simple example 4 +5 = 9 In the example,4and5is calledoperand,+is called an operator.

The Python language supports the following types of operators:

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


Python Arithmetic Operators

The following assumes variables: a=10,b=20:

OperatorDescriptionExample
+Addition - Adds two objectsa + b outputs 30
-Subtraction - Gives a negative number or subtracts one number from anothera - b outputs -10
*Multiplication - Multiplies two numbers or returns a string repeated a number of timesa * b outputs 200
/Division - x divided by yb / a outputs 2
%Modulus - Returns the remainder of divisionb % a outputs 0
**Exponent - Returns x raised to the power ya**b is 10 to the 20th power, outputs 100000000000000000000
//Floor division - Returns the integer part of the quotient (rounded down)
>>> 9//2
4
>>> -9//2
-5

The following example demonstrates the operations of all Python arithmetic operators:

Examples (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- 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 the values of variables a, b, 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

Run example »

The output of the above example is:

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

Note:In Python 2.x, integer divided by integer can only yield an integer. If you want the fractional part, change one of the numbers to a float.

>>> 1/2
0
>>> 1.0/2
0.5
>>> 1/float(2)
0.5

Python Comparison Operators

The following assumes variable a is 10 and variable b is 20:

OperatorDescriptionExample
==Equals - Compares whether objects are equal(a == b) returns False.
!=Not equal - Compares whether two objects are not equal(a != b) returns True.
<>Not equal - Compares whether two objects are not equal.Deprecated in Python 3.(a <> b) returns True. This operator is similar to !=.
>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. These are equivalent to the special variables True and False, respectively.(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 the operations of all Python comparison operators:

Examples (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- a = 21 b = 10 c = 0 if a == b : print "1 - a equals b" else: print "1 - a is not equal to b" if a != b : print "2 - a is not equal to b" else: print "2 - a equals b" if a <> b : print "3 - a is not equal to b" else: print "3 - a equals b" if a < b : print "4 - a is less than b" else: print "4 - a is greater than or equal to b" if a > b : print "5 - a is greater than b" else: print "5 - a is less than or equal to b" # Modify the values of variables a and b a = 5 b = 20 if a <= b : print "6 - a is less than or equal to b" else: print "6 - a is greater than b" if b >= a : print "7 - b is greater than or equal to a" else: print "7 - b is less than a"

The output of the above example is:

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

Python Assignment Operators

The following assumes variable a is 10 and variable b is 20:

OperatorDescriptionExample
=Simple assignment operatorc = a + b assigns the result of a + b to c
+=Addition assignment operatorc += a is equivalent to c = c + a
-=Subtraction assignment operatorc -= a is equivalent to c = c - a
*=Multiplication assignment operatorc *= a is equivalent to c = c * a
/=Division assignment operatorc /= a is equivalent to c = c / a
%=Modulus assignment operatorc %= a is equivalent to c = c % a
**=Exponent assignment operatorc **= a is equivalent to c = c ** a
//=Floor division assignment operatorc //= a is equivalent to c = c // a

The following example demonstrates the operations of all Python assignment operators:

Examples (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- 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 output of the above example is:

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

Python Bitwise Operators

Bitwise operators treat numbers as binary for calculation. The bitwise operation rules in Python are as follows:

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

a = 0011 1100

b = 0000 1101

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

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a  = 1100 0011
OperatorDescriptionExample
&Bitwise AND operator: For the two values involved in the operation, if both corresponding bits are 1, the result bit is 1; otherwise, it is 0.(a & b) outputs 12, binary explanation: 0000 1100
|Bitwise OR operator: As long as one of the two corresponding binary bits is 1, the result bit is 1.(a | b) outputs 61, binary explanation: 0011 1101
^Bitwise XOR operator: When the two corresponding binary bits are different, the result is 1.(a ^ b) outputs 49, binary explanation: 0011 0001
~Bitwise NOT operator: Inverts each bit in the binary representation, changing 0 to 1 and 1 to 0.~xSimilar to-x-1(~a ) outputs -61, binary explanation: 1100 0011 (represented in two's complement form), in the two's complement form of a signed binary number.
<<Left shift operator: All binary bits of the operand are shifted left by a number of bits, determined by<<The number on the right specifies the number of positions to shift. High-order bits are discarded, and low-order bits are filled with 0.a << 2 outputs 240, binary explanation: 1111 0000
>>Right shift operator: shifts all binary bits of the operand on the left of ">>" to the right by the specified number of places,>>The number on the right specifies the number of positions to shift.a >> 2 outputs 15, binary explanation: 0000 1111

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

Examples (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- 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 output of the above example is:

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

Python Logical Operators

Python language supports logical operators. Assume variable a is 10 and b is 20:

OperatorLogical expressionDescriptionExample
andx and yBoolean "and" - If x is False, x and y returns False, otherwise it returns the evaluated value of y.(a and b) returns 20.
orx or yBoolean "or" - If x is non-zero, it returns the evaluated value of x, otherwise it returns the evaluated value of y.(a or b) returns 10.
notnot xBoolean "not" - If x is True, returns False. If x is False, it returns True.not(a and b) returns False

The output of the above example is:

Examples (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- 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 the variables is True" else: print "2 - variables a and b are both not 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 the variables is True" else: print "4 - variables a and b are both not True" if not( a and b ): print "5 - variables a and b are both False, or one of the variables is False" else: print "5 - variables a and b are both True"

The output of the above example is:

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 a series of members, including strings, lists, or tuples.

OperatorDescriptionExample
inReturns True if the value is found in the specified sequence, otherwise returns False. x in y sequence, returns True if x is in the y sequence.
not inReturns True if the value is not found in the specified sequence, otherwise returns False. x not in y sequence, returns True if x is not in the y sequence.

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

Examples (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- 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 output of the above example is:

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

Python Identity Operators

Identity operators are used to compare the storage units of two objects

OperatorDescriptionExample
isis determines whether two identifiers reference the same object x is y, similar toid(x) == id(y), if they reference the same object, returns True; otherwise returns False
is notis not determines whether two identifiers reference different objects x is not y, similar toid(a) != id(b). If they do not reference the same object, the result returns True; otherwise returns False.

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

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

Examples (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- 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 ( a is not b ): print "2 - a and b do not have the same identity" else: print "2 - a and b 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 output of the above example is:

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

Difference between is and ==:

is is used to determine whether two variable references refer to the same object (the same memory space), == is used to determine 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 following table lists all operators from highest to lowest precedence:

OperatorDescription
** Exponentiation (highest precedence)
~ + - Bitwise inversion, unary plus and minus (the method names for the last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+ - Addition and subtraction
>> << Right shift, left shift operators
& Bitwise 'AND'
^ | Bitwise operators
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= **= Assignment operators
is is not Identity operators
in not in Membership operators
not and or Logical operators

The following example demonstrates the operations of all operator precedence in Python:

Examples (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- a = 20 b = 10 c = 15 d = 5 e = 0 e = (a + b) * c / d #( 30 * 15 ) / 5 print "The result of (a + b) * c / d is:", e e = ((a + b) * c) / d # (30 * 15 ) / 5 print "The result of ((a + b) * c) / d is:", e e = (a + b) * (c / d); # (30) * (15/5) print "The result of (a + b) * (c / d) is:", e e = a + (b * c) / d; # 20 + (150/5) print "The result of a + (b * c) / d is:", e

The output of the above example is:

(a + b) * c / d 运算结果为: 90
((a + b) * c) / d 运算结果为: 90
(a + b) * (c / d) 运算结果为: 90
a + (b * c) / d 运算结果为: 50
Other extensions