Python Tutorial (9) - Operators

Time: Column:Python views:220

What Are Operators?

This section mainly explains the concept of operators in Python.

Here’s a simple example:

4 + 5 = 9

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

Python supports the following types of operators:

  • Arithmetic Operators

  • Comparison (Relational) Operators

  • Assignment Operators

  • Logical Operators

  • Bitwise Operators

  • Membership Operators

  • Identity Operators

  • Operator Precedence

Next, let's go through each of these operators in Python.


Python Arithmetic Operators

Assume a = 10 and b = 21 for the following examples:

OperatorDescriptionExample
+Addition - Adds two operandsa + b results in 31
-Subtraction - Subtracts one operand from anothera - b results in -11
*Multiplication - Multiplies two operandsa * b results in 210
/Division - Divides one operand by anotherb / a results in 2.1
%Modulus - Returns the remainder of the divisionb % a results in 1
**Exponent - Raises one operand to the power of anothera**b gives 10 to the power of 21
//Floor Division - Divides and rounds down to the nearest integer9//2 results in 4, -9//2 results in -5

Below is an example demonstrating the use of all arithmetic operators in Python:

#!/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 output of the above code would be:

1 - The value of c is: 31
2 - The value of c is: 11
3 - The value of c is: 210
4 - The value of c is: 2.1
5 - The value of c is: 1
6 - The value of c is: 8
7 - The value of c is: 2

Python Comparison Operators

Assume a = 10 and b = 20 for the following examples:

OperatorDescriptionExample
==Equal to - Compares if two values are equal(a == b) returns False
!=Not equal to - Compares if two values are not equal(a != b) returns True
>Greater than - Checks if one value is greater than another(a > b) returns False
<Less than - Checks if one value is less than another(a < b) returns True
>=Greater than or equal to - Checks if one value is greater than or equal to another(a >= b) returns False
<=Less than or equal to - Checks if one value is less than or equal to another(a <= b) returns True

Below is an example demonstrating the use of all comparison operators in Python:

#!/usr/bin/python3

a = 21
b = 10
c = 0

if (a == b):
    print("1 - a is equal to 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 is equal to 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 values of 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 output of the above code would be:

plaintext複製程式碼1 - a is not equal to b
2 - a is not equal to b
3 - a is greater than or equal to b
4 - a is greater than b
5 - a is less than or equal to b
6 - b is greater than or equal to a

Python Assignment Operators

Assume that the variable a is 10 and b is 20 for the following examples:

OperatorDescriptionExample
=Simple assignment operatorc = a + b assigns the result of a + b to c
+=Add AND assignment operatorc += a is equivalent to c = c + a
-=Subtract AND assignment operatorc -= a is equivalent to c = c - a
*=Multiply AND assignment operatorc *= a is equivalent to c = c * a
/=Divide AND assignment operatorc /= a is equivalent to c = c / a
%=Modulus AND assignment operatorc %= a is equivalent to c = c % a
**=Exponent AND assignment operatorc **= a is equivalent to c = c ** a
//=Floor Division AND assignment operatorc //= a is equivalent to c = c // a
:=Walrus operator (Python 3.8+), assigns and returns the valueif (n := len(a)) > 10: Avoids calling len() twice.

Here is an example demonstrating the usage of all assignment operators in Python:

#!/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 output of the above code would be:

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



Walrus Operator (Python 3.8+)

In Python 3.8 and higher versions, a new syntax feature was introduced called the walrus operator (:=). This operator allows for assignment and returning of a value in a single expression.

The walrus operator can simplify code by avoiding redundant calculations, particularly when the result of an expression is used multiple times. It is especially useful for reducing repetition in loop conditions or expressions.

Here’s a simple example demonstrating the usage of the walrus operator:

# Traditional approach
n = 10
if n > 5:
    print(n)

# Using the walrus operator
if (n := 10) > 5:
    print(n)

Explanation:

  • (n := 10) assigns the value 10 to n and simultaneously returns this value.

  • The > 5 checks if the assigned value of n is greater than 5.

  • If the condition is true, the code prints the value of n (which is 10).

Advantages of the Walrus Operator:

The walrus operator (:=) allows assignment inside expressions, reducing repetition and improving readability and conciseness of the code. In the above example, the traditional method required separate lines for assignment and the condition check, while the walrus operator allowed them to be combined.


Python Bitwise Operators

Bitwise operators treat numbers as binary and operate on them bit by bit. The following bitwise operators are supported in Python:

Assume a = 60 and b = 13 with binary representations as follows:

  • a = 0011 1100

  • b = 0000 1101

OperatorDescriptionExample
&Bitwise AND - Each bit is compared, and the result is 1 if both corresponding bits are 1, otherwise 0.a & b results in 12 (0000 1100)
``Bitwise OR - The result is 1 if at least one corresponding bit is 1.
^Bitwise XOR - The result is 1 if the corresponding bits are different.a ^ b results in 49 (0011 0001)
~Bitwise NOT - Inverts the bits, turning 1 to 0 and 0 to 1.~a results in -61 (1100 0011)
<<Left Shift - Shifts the bits to the left, filling with zeros from the right.a << 2 results in 240 (1111 0000)
>>Right Shift - Shifts the bits to the right, filling with zeros from the left.a >> 2 results in 15 (0000 1111)

Here is an example demonstrating all the bitwise operators in Python:

#!/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 output of the above code would be:

1 - The value of c is: 12
2 - The value of c is: 61
3 - The value of c is: 49
4 - The value of c is: -61
5 - The value of c is: 240
6 - The value of c is: 15

Python Logical Operators

Python supports logical operators. Assuming a = 10 and b = 20, the following explains their usage:

OperatorLogical ExpressionDescriptionExample
andx and yLogical AND - Returns the value of x if x is False; otherwise, it returns the evaluated value of y.(a and b) returns 20.
orx or yLogical OR - Returns the value of x if x is True; otherwise, it returns the evaluated value of y.(a or b) returns 10.
notnot xLogical NOT - Returns False if x is True; returns True if x is False.not(a and b) returns False.

Here is an example demonstrating Python's logical operators:

#!/usr/bin/python3

a = 10
b = 20

if (a and b):
    print("1 - Both variables a and b are true")
else:
    print("1 - One of the variables a or b is not true")

if (a or b):
    print("2 - Either both variables a and b are true, or one of them is true")
else:
    print("2 - Neither variable a nor b is true")

# Modifying the value of variable a
a = 0
if (a and b):
    print("3 - Both variables a and b are true")
else:
    print("3 - One of the variables a or b is not true")

if (a or b):
    print("4 - Either both variables a and b are true, or one of them is true")
else:
    print("4 - Neither variable a nor b is true")

if not (a and b):
    print("5 - Both variables a and b are false, or one of them is false")
else:
    print("5 - Both variables a and b are true")

The output of the above code would be:

1 - Both variables a and b are true
2 - Either both variables a and b are true, or one of them is true
3 - One of the variables a or b is not true
4 - Either both variables a and b are true, or one of them is true
5 - Both variables a and b are false, or one of them is false

Python Membership Operators

In addition to the above operators, Python supports membership operators to test whether a value exists in a sequence such as strings, lists, or tuples.

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

Here is an example demonstrating Python's membership operators:

#!/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")

# Modifying 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 code would be:

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

Python Identity Operators

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

OperatorDescriptionExample
isEvaluates if two variables point to the same object in memory.x is y is equivalent to id(x) == id(y). Returns True if they refer to the same object, otherwise returns False.
is notEvaluates if two variables point to different objects in memory.x is not y is equivalent to id(x) != id(y). Returns True if they refer to different objects, otherwise returns False.

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

Below is an example demonstrating Python identity operators:

#!/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")

# Modifying 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 code would be:

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: Checks whether two variables refer to the same object in memory.

  • ==: Compares whether the values of two variables are equal.

Example:

>>> 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 Python operators from highest to lowest precedence. Operators in the same cell share the same precedence. Operators are generally evaluated from left to right (except for exponentiation, which is evaluated right to left).

OperatorsDescription
(expressions...), [expressions...], {key: value...}, {expressions...}Tuple, list, set, and dictionary displays
x[index], x[index:index], x(arguments...), x.attributeSubscript, slice, call, attribute reference
await xAwait expression
**Exponentiation
+x, -x, ~xUnary plus, minus, bitwise NOT
*, @, /, //, %Multiplication, matrix multiplication, division, floor division, remainder
+, -Addition and subtraction
<<, >>Bitwise shift operators
&Bitwise AND
^Bitwise XOR
``
in, not in, is, is not, <, <=, >, >=, !=, ==Comparisons, including membership and identity
not xLogical NOT
andLogical AND
orLogical OR
if -- elseConditional expression
lambdaLambda expression
:=Assignment expression

Here is an example demonstrating Python's operator precedence:

#!/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 code would be:

(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 Than or

Example:

x = True
y = False
z = False

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

The result of y and z is False, and x or False evaluates to True. The output is:

yes

Note: Python 3 no longer supports the <> operator. You can use != instead. If you still want to use the old comparison operator, you can do so like this:

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