Python 3 operators

Python 3 Operators


What are Operators?

This chapter explains Python operators. Let’s take a simple example: 4 + 5 = 9.
In this example, 4 and 5 are called operands, and “+” is called the operator.

The Python language 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 learn about Python operators one by one.


Python Arithmetic Operators

Assume that variable a holds 10 and variable b holds 21:

Operator Description Example
+ Addition – Adds two objects together a + b outputs 31
Subtraction – Negates a number or subtracts one from another a – b outputs -11
* Multiplication – Multiplies two numbers together or returns a string repeated a certain number of times a * b outputs 210
/ Division – x divided by y b / a outputs 2.1
% Modulo – Returns the remainder of division b % a outputs 1
** Power – Returns x raised to the power of y a**b is 10 raised to the power of 21
// Division – Rounds down to the nearest integer
>>> 9//2
4
>>> -9//2
-5

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

Example (Python 3.0+)

<code>#!/usr/bin/python3

a = 21
b = 10
c = 0

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

c = a - b
print ("The value of 2 - c is:", c)

c = a * b
print ("The value of 3 - c is:", c)

c = a / b
print ("The value of 4 - c is:", c)

c = a % b
print ("The value of 5 - c is:", c)

# Modify variables a, b, and c
a = 2
b = 3
c = a**b
print ("The value of 6 - c is:", c)

a = 10
b = 5
c = a//b
print ("The value of 7 - c is:", c)

The output of the above example is:

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

Python Comparison Operators

Assume that variable a holds 10 and variable b holds 20:

Operator Description Example
== Equal – Compares whether two objects are equal. (a == b) returns False.
!= Not equal – Compares whether two objects are unequal. (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. These are equivalent to the special variables True and False, respectively. Note the capitalization of these variable names. (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 operation of all Python comparison operators:

Example (Python 3.0+)

<code>#!/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") 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 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 or equal to b")

if ( b >= a ):
print ("6 - b is greater than or equal to a")
else:
print ("6 - b is less than or equal to a")

The above example outputs:

1 - a is not equal to b
2 - a is not equal to b
3 - a 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 variable a is 10 and variable b is 20:

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
**= Power assignment operator c **= a is equivalent to c = c ** a
//= Integer division assignment operator c //= a is equivalent to c = c // a
:= The walrus operator can be used to assign values to variables within expressions. New 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 the operation of all Python assignment operators:

Example (Python 3.0+)

<code>#!/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 ("The value of 4 - c is: ", c)

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

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

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

The above example outputs:

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

Python Bitwise Operators

Bitwise operators perform calculations on numbers as binary. The bitwise operations in Python are as follows:

In the following table, variables a and b are 60 and 13, respectively. The binary format is 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 operator: If both corresponding bits of the two values involved in the operation are 1, the result for that bit is 1; otherwise, it is 0. (a & b) outputs 12, binary interpretation: 0000 1100.
| Bitwise OR operator: If either of the two corresponding binary bits is 1, the result is 1. (a | b) outputs 61, binary interpretation: 0011 1101
^ Bitwise exclusive OR operator: When two corresponding binary bits are different, the result is 1. (a ^ b) outputs 49, binary interpretation: 0011 0001
~ Bitwise inversion operator: Inverts each binary bit of the data, turning 1s to 0s and 0s to 1s. ~x is similar to -x-1. (~a) outputs -61, binary interpretation: 1100 0011, in two’s complement form.
<< Left shift operator: Shifts all binary digits of the operand left by a certain number of bits, as specified by the number to the right of the “<<" operator. High-order bits are discarded, and low-order bits are padded with 0s. a << 2 outputs 240, binary interpretation: 1111 0000
>> Right shift operator: shifts all binary digits of the operand to the left of the “>>” operator to the right by a certain number of bits. The number to the right of the “>>” operator specifies the number of bits to shift. a >> 2 outputs 15, binary interpretation: 0000 1111

The following example demonstrates the operation of all Python bitwise operators:

Example (Python 3.0+)

<code>#!/usr/bin/python3

a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c = 0

c = a & b; # 12 = 0000 1100
print ("1 - c is:", c)

c = a | b; # 61 = 0011 1101
print ("2 - c is:", c)

c = a ^ b; # 49 = 0011 0001
print ("3 - c is:", c)

c = ~a; # -61 = 1100 0011
print ("4 - c is:", c)

c = a << 2; # 240 = 1111 0000
print ("5 - c is:", c)

c = a >> 2; # 15 = 0000 1111
print ("6 - c is:", c)

The above example outputs:

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

The Python language supports logical operators. Assume that variables a is 10 and b is 20:

Operator Logical Expression Description Example
and x and y Boolean AND – If If x is False, x and y returns False; 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, it returns False. If x is False, it returns True. not(a and b) returns False

The above example outputs:

Example (Python 3.0+)

<code>#!/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 - Variable a is true") Both a and b are true")
else:
print ("3 - One of variables a and b is not true")

if ( a or b ):
print ("4 - 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 above example outputs:

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

Python Membership Operators

In addition to the operators listed above, Python supports membership operators that test instances containing a sequence of members, including strings, lists, or tuples.

Operator Description Example
in Returns True if the value is found in the specified sequence, otherwise returns 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 returns False. x is not in the y sequence. Returns True if x is not in the y sequence.

The following example demonstrates the operation of all Python member operators:

Example (Python 3.0+)

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

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

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

The above example outputs:

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

Python Identity Operator

The identity operator is used to compare the storage units of two objects

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

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

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

Example (Python 3.0+)

<code>#!/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 above example outputs:

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

Differences between is and ==:

is is used to determine whether two variables reference the same object, while == 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:

Operator Description
** Exponential (highest precedence)
~ + – Bitwise flip, unary plus and minus (the last two have methods named +@ and -@)
* / % // Multiplication, Division, Remainder, and Integer Division
+ – Addition and Subtraction
>> << Right and Left Shift Operators
& Bitwise ‘AND’
^ | Bitwise Operators
<= < > >= Comparison Operators
== != Equality Operator
= %= /= //= -= += *= **= Assignment Operator
is is not Identity Operator
in not in Membership Operator
not and or Logical Operator

The following example demonstrates the operation of all Python operator precedence:

Example (Python 3.0+)

<code>#!/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 Calculation Result is:", e)

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

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

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

The above example outputs:

(a + b) * c / d results in: 90.0
((a + b) * c) / d results in: 90.0
(a + b) * (c / d) results in: 90.0
a + (b * c) / d results in: 50.0

and has higher priority:

Example

<code>x = True
y = False
z = False

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

The above example outputs:

yes

Note: Python 3 no longer supports the <> operator. You can use != instead. If you must use this comparison operator, you can use the following method:

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

Leave a Reply

Your email address will not be published. Required fields are marked *