Open In App

Python Operators

Last Updated : 30 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. 

  • OPERATORS: These are the special symbols. Eg- + , * , /, etc.
  • OPERAND: It is the value on which the operator is applied.

Types of Operators in Python

  1. Arithmetic Operators
  2. Comparison Operators
  3. Logical Operators
  4. Bitwise Operators
  5. Assignment Operators
  6. Identity Operators and Membership Operators

Python Operators

Arithmetic Operators in Python

Python Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication, and division.

In Python 3.x the result of division is a floating-point while in Python 2.x division of 2 integers was an integer. To obtain an integer result in Python 3.x floored (// integer) is used.

Operator Description Syntax
+ Addition: adds two operands x + y
Subtraction: subtracts two operands x – y
* Multiplication: multiplies two operands x * y
/ Division (float): divides the first operand by the second x / y
// Division (floor): divides the first operand by the second x // y
% Modulus: returns the remainder when the first operand is divided by the second x % y
** Power: Returns first raised to power second x ** y

Example of Arithmetic Operators in Python

Division Operators

In Python programming language Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. 

There are two types of division operators: 

  1. Float division
  2. Floor division

Float division

The quotient returned by this operator is always a float number, no matter if two numbers are integers. For example:

Example: The code performs division operations and prints the results. It demonstrates that both integer and floating-point divisions return accurate results. For example, ’10/2′ results in ‘5.0’, and ‘-10/2’ results in ‘-5.0’.

[GFGTABS] Python

print(5/5)
print(10/2)
print(-10/2)
print(20.0/2)

[/GFGTABS]

Output:

1.0
5.0
-5.0
10.0

Integer division( Floor division)

The quotient returned by this operator is dependent on the argument being passed. If any of the numbers is float, it returns output in float. It is also known as Floor division because, if any number is negative, then the output will be floored. For example:

Example: The code demonstrates integer (floor) division operations using the // in Python operators. It provides results as follows: ’10//3′ equals ‘3’, ‘-5//2’ equals ‘-3’, ‘5.0//2′ equals ‘2.0’, and ‘-5.0//2’ equals ‘-3.0’. Integer division returns the largest integer less than or equal to the division result.

[GFGTABS] Pythons

print(10//3)
print (-5//2)
print (5.0//2)
print (-5.0//2)

[/GFGTABS]

Output:

3
-3
2.0
-3.0

Precedence of Arithmetic Operators in Python

The precedence of Arithmetic Operators in Python is as follows:

  1. P – Parentheses
  2. E – Exponentiation
  3. M – Multiplication (Multiplication and division have the same precedence)
  4. D – Division
  5. A – Addition (Addition and subtraction have the same precedence)
  6. S – Subtraction

The modulus of Python operators helps us extract the last digit/s of a number. For example:

  • x % 10 -> yields the last digit
  • x % 100 -> yield last two digits

Arithmetic Operators With Addition, Subtraction, Multiplication, Modulo and Power

Here is an example showing how different Arithmetic Operators in Python work:

Example: The code performs basic arithmetic operations with the values of ‘a’ and ‘b’. It adds (‘+’), subtracts (‘-‘), multiplies (‘*’), computes the remainder (‘%’), and raises a to the power of ‘b (**)’. The results of these operations are printed.

[GFGTABS] Python

a = 9
b = 4
add = a + b

sub = a - b

mul = a * b

mod = a % b

p = a ** b
print(add)
print(sub)
print(mul)
print(mod)
print(p)

[/GFGTABS]

Output:

13
5
36
1
6561

Note: Refer to Differences between / and // for some interesting facts about these two Python operators.

Comparison of Python Operators

In Python Comparison of Relational operators compares the values. It either returns True or False according to the condition.

Operator Description Syntax
> Greater than: True if the left operand is greater than the right x > y
< Less than: True if the left operand is less than the right x < y
== Equal to: True if both operands are equal x == y
!= Not equal to – True if operands are not equal x != y
>= Greater than or equal to True if the left operand is greater than or equal to the right x >= y
<= Less than or equal to True if the left operand is less than or equal to the right x <= y

= is an assignment operator and == comparison operator.

Precedence of Comparison Operators in Python

In Python, the comparison operators have lower precedence than the arithmetic operators. All the operators within comparison operators have the same precedence order.

Example of Comparison Operators in Python

Let’s see an example of Comparison Operators in Python.

Example: The code compares the values of ‘a’ and ‘b’ using various comparison Python operators and prints the results. It checks if ‘a’ is greater than, less than, equal to, not equal to, greater than, or equal to, and less than or equal to ‘b’.

[GFGTABS] Python

a = 13
b = 33

print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)

[/GFGTABS]

Output

False
True
False
True
False
True



Logical Operators in Python

Python Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used to combine conditional statements.

Operator Description Syntax
and Logical AND: True if both the operands are true x and y
or Logical OR: True if either of the operands is true  x or y
not Logical NOT: True if the operand is false  not x

Precedence of Logical Operators in Python

The precedence of Logical Operators in Python is as follows:

  1. Logical not
  2. logical and
  3. logical or

Example of Logical Operators in Python

The following code shows how to implement Logical Operators in Python:

Example: The code performs logical operations with Boolean values. It checks if both ‘a’ and ‘b’ are true (‘and’), if at least one of them is true (‘or’), and negates the value of ‘a’ using ‘not’. The results are printed accordingly.

[GFGTABS] Python

a = True
b = False
print(a and b)
print(a or b)
print(not a)

[/GFGTABS]

Output

False
True
False



Bitwise Operators in Python

Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to operate on binary numbers.

Operator Description Syntax
& Bitwise AND x & y
| Bitwise OR x | y
~ Bitwise NOT ~x
^ Bitwise XOR x ^ y
>> Bitwise right shift x>>
<< Bitwise left shift x<<

Precedence of Bitwise Operators in Python

The precedence of Bitwise Operators in Python is as follows:

  1. Bitwise NOT
  2. Bitwise Shift
  3. Bitwise AND
  4. Bitwise XOR
  5. Bitwise OR

Bitwise Operators in Python

Here is an example showing how Bitwise Operators in Python work:

Example: The code demonstrates various bitwise operations with the values of ‘a’ and ‘b’. It performs bitwise AND (&), OR (|), NOT (~), XOR (^), right shift (>>), and left shift (<<) operations and prints the results. These operations manipulate the binary representations of the numbers.

[GFGTABS] Python

a = 10
b = 4
print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)

[/GFGTABS]

Output

0
14
-11
14
2
40



Assignment Operators in Python

Python Assignment operators are used to assign values to the variables.

Operator Description Syntax
= Assign the value of the right side of the expression to the left side operand  x = y + z
+= Add AND: Add right-side operand with left-side operand and then assign to left operand a+=b     a=a+b
-= Subtract AND: Subtract right operand from left operand and then assign to left operand a-=b     a=a-b
*= Multiply AND: Multiply right operand with left operand and then assign to left operand a*=b     a=a*b
/= Divide AND: Divide left operand with right operand and then assign to left operand a/=b     a=a/b
%= Modulus AND: Takes modulus using left and right operands and assign the result to left operand a%=b     a=a%b
//= Divide(floor) AND: Divide left operand with right operand and then assign the value(floor) to left operand a//=b     a=a//b
**= Exponent AND: Calculate exponent(raise power) value using operands and assign value to left operand a**=b     a=a**b
&= Performs Bitwise AND on operands and assign value to left operand a&=b     a=a&b
|= Performs Bitwise OR on operands and assign value to left operand a|=b     a=a|b
^= Performs Bitwise xOR on operands and assign value to left operand a^=b     a=a^b
>>= Performs Bitwise right shift on operands and assign value to left operand a>>=b     a=a>>b
<<= Performs Bitwise left shift on operands and assign value to left operand a <<= b     a= a << b

Assignment Operators in Python

Let’s see an example of Assignment Operators in Python.

Example: The code starts with ‘a’ and ‘b’ both having the value 10. It then performs a series of operations: addition, subtraction, multiplication, and a left shift operation on ‘b’. The results of each operation are printed, showing the impact of these operations on the value of ‘b’.

[GFGTABS] Python

a = 10
b = a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)

[/GFGTABS]

Output

10
20
10
100
102400



Identity Operators in Python

In Python, is and is not are the identity operators both are used to check if two values are located on the same part of the memory. Two variables that are equal do not imply that they are identical. 

is          True if the operands are identical 
is not True if the operands are not identical

Example Identity Operators in Python

Let’s see an example of Identity Operators in Python.

Example: The code uses identity operators to compare variables in Python. It checks if ‘a’ is not the same object as ‘b’ (which is true because they have different values) and if ‘a’ is the same object as ‘c’ (which is true because ‘c’ was assigned the value of ‘a’).

[GFGTABS] Python

a = 10
b = 20
c = a

print(a is not b)
print(a is c)

[/GFGTABS]

Output

True
True



Membership Operators in Python

In Python, in and not in are the membership operators that are used to test whether a value or variable is in a sequence.

in            True if value is found in the sequence
not in True if value is not found in the sequence

Examples of Membership Operators in Python

The following code shows how to implement Membership Operators in Python:

Example: The code checks for the presence of values ‘x’ and ‘y’ in the list. It prints whether or not each value is present in the list. ‘x’ is not in the list, and ‘y’ is present, as indicated by the printed messages. The code uses the ‘in’ and ‘not in’ Python operators to perform these checks.

[GFGTABS] Python

x = 24
y = 20
list = [10, 20, 30, 40, 50]

if (x not in list):
    print("x is NOT present in given list")
else:
    print("x is present in given list")

if (y in list):
    print("y is present in given list")
else:
    print("y is NOT present in given list")

[/GFGTABS]

Output

x is NOT present in given list
y is present in given list



Ternary Operator in Python

in Python, Ternary operators also known as conditional expressions are operators that evaluate something based on a condition being true or false. It was added to Python in version 2.5. 

It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.

Syntax :  [on_true] if [expression] else [on_false] 

Examples of Ternary Operator in Python

The code assigns values to variables ‘a’ and ‘b’ (10 and 20, respectively). It then uses a conditional assignment to determine the smaller of the two values and assigns it to the variable ‘min’. Finally, it prints the value of ‘min’, which is 10 in this case.

[GFGTABS] Python

a, b = 10, 20
min = a if a < b else b

print(min)

[/GFGTABS]

Output: 

10

Precedence and Associativity of Operators in Python

In Python, Operator precedence and associativity determine the priorities of the operator.

Operator Precedence in Python

This is used in an expression with more than one operator with different precedence to determine which operation to perform first.

Let’s see an example of how Operator Precedence in Python works:

Example: The code first calculates and prints the value of the expression 10 + 20 * 30, which is 610. Then, it checks a condition based on the values of the ‘name’ and ‘age’ variables. Since the name is “Alex” and the condition is satisfied using the or operator, it prints “Hello! Welcome.”

[GFGTABS] Python

expr = 10 + 20 * 30
print(expr)
name = "Alex"
age = 0

if name == "Alex" or name == "John" and age >= 2:
    print("Hello! Welcome.")
else:
    print("Good Bye!!")

[/GFGTABS]

Output

610
Hello! Welcome.



Operator Associativity in Python

If an expression contains two or more operators with the same precedence then Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.

The following code shows how Operator Associativity in Python works:

Example: The code showcases various mathematical operations. It calculates and prints the results of division and multiplication, addition and subtraction, subtraction within parentheses, and exponentiation. The code illustrates different mathematical calculations and their outcomes.

[GFGTABS] Python

print(100 / 10 * 10)
print(5 - 2 + 3)
print(5 - (2 + 3))
print(2 ** 3 ** 2)

[/GFGTABS]

Output

100.0
6
0
512



To try your knowledge of Python Operators, you can take out the quiz on Operators in Python. 

Python Operator Exercise Questions

Below are two Exercise Questions on Python Operators. We have covered arithmetic operators and comparison operators in these exercise questions. For more exercises on Python Operators visit the page mentioned below.

Q1. Code to implement basic arithmetic operations on integers

[GFGTABS] Python

num1 = 5
num2 = 2
sum = num1 + num2
difference = num1 - num2
product = num1 * num2
quotient = num1 / num2 
remainder = num1 % num2
print("Sum:", sum)
print("Difference:", difference)
print("Product:", product)
print("Quotient:", quotient)
print("Remainder:", remainder)

[/GFGTABS]

Output

Sum: 7
Difference: 3
Product: 10
Quotient: 2.5
Remainder: 1

Q2. Code to implement Comparison operations on integers

[GFGTABS] Python

num1 = 30
num2 = 35
if num1 > num2:
    print("The first number is greater.")
elif num1 < num2:
    print("The second number is greater.")
else:
    print("The numbers are equal.")

[/GFGTABS]

Output

The second number is greater.

Explore more Exercises: Practice Exercise on Operators in Python



Next Article

Similar Reads

Python | Operators | Question 1
What is the output of the following code : C/C++ Code print 9//2 (A) 4.5 (B) 4.0 (C) 4 (D) Error Answer: (C)Explanation: The ‘//’ operator in Python returns the integer part of the floating number. Quiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
Python | Operators | Question 2
Which function overloads the >> operator? (A) more() (B) gt() (C) ge() (D) None of the above Answer: (D) Explanation: rshift() overloads the >> operatorQuiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
Python | Operators | Question 3
Which operator is overloaded by the or() function? (A) || (B) | (C) // (D) / Answer: (B) Explanation: or() function overloads the bitwise OR operatorQuiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
Python | Operators | Question 4
What is the output of the following program : C/C++ Code i = 0 while i (A) 0 2 1 3 2 4 (B) 0 1 2 3 4 5 (C) Error (D) 1 0 2 4 3 5 Answer: (C)Explanation: There is no operator ++ in Python Quiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
Merging and Updating Dictionary Operators in Python 3.9
Python 3.9 is still in development and scheduled to be released in October this year. On Feb 26, alpha 4 versions have been released by the development team. One of the latest features in Python 3.9 is the merge and update operators. There are various ways in which Dictionaries can be merged by the use of various functions and constructors in Pytho
3 min read
Python 3 - Logical Operators
Logical Operators are used to perform certain logical operations on values and variables. These are the special reserved keywords that carry out some logical computations. The value the operator operates on is known as Operand. In Python, they are used on conditional statements (either True or False), and as a result, they return boolean only (True
4 min read
How To Do Math in Python 3 with Operators?
Python3 provides us data types like integer and float along with various operators to perform mathematical calculations for graph plotting, machine learning algorithms, Statistical, data analytical purposes. An operator is a symbol that performs specific operations, which is very useful if one is frequently dealing with numbers. Operator precedence
5 min read
Precedence and Associativity of Operators in Python
In Python, operators have different levels of precedence, which determine the order in which they are evaluated. When multiple operators are present in an expression, the ones with higher precedence are evaluated first. In the case of operators with the same precedence, their associativity comes into play, determining the order of evaluation. Opera
4 min read
Augmented Assignment Operators in Python
An assignment operator is an operator that is used to assign some value to a variable. Like normally in Python, we write "a = 5" to assign value 5 to variable 'a'. Augmented assignment operators have a special role to play in Python programming. It basically combines the functioning of the arithmetic or bitwise operator with the assignment operator
4 min read
Inplace Operators in Python | Set 1 (iadd(), isub(), iconcat()...)
Python in its definition provides methods to perform inplace operations, i.e. doing assignments and computations in a single statement using an operator module. Example x += y is equivalent to x = operator.iadd(x, y) Inplace Operators in PythonBelow are some of the important Inplace operators in Python: iadd()isub()iconcat()imul()itruediv()imod()ia
3 min read
Inplace Operators in Python | Set 2 (ixor(), iand(), ipow(),…)
Inplace Operators in Python | Set 1(iadd(), isub(), iconcat()…) More functions are discussed in this articles. 1. ixor() :- This function is used to assign and xor the current value. This operation does "a^ = b" operation. Assigning is not performed in case of immutable containers, such as strings, numbers and tuples. 2. ipow() :- This function is
3 min read
Inplace vs Standard Operators in Python
Inplace Operators - Set 1, Set 2Normal operators do the simple assigning job. On other hand, Inplace operators behave similarly to normal operators except that they act in a different manner in case of mutable and Immutable targets. The _add_ method, does simple addition, takes two arguments, returns the sum, and stores it in another variable witho
3 min read
Chaining comparison operators in Python
Checking more than two conditions is very common in Programming Languages. Let's say we want to check the below condition: a < b < c The most common syntax to do it is as follows: if a < b and b < c : {...} In Python, there is a better way to write this using the Comparison operator Chaining. The chaining of operators can be written as
5 min read
Increment += and Decrement -= Assignment Operators in Python
If you're familiar with Python, you would have known Increment and Decrement operators ( both pre and post) are not allowed in it. Python is designed to be consistent and readable. One common error by a novice programmer in languages with ++ and -- operators are mixing up the differences (both in precedence and in return value) between pre and post
3 min read
Division Operators in Python
Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. Division Operators in PythonThere are two types of division operators: Float divisionInteger division( Floor division)When an integer is divided, the
6 min read
Why Are There No ++ and -- Operators in Python?
Python does not include the ++ and -- operators that are common in languages like C, C++, and Java. This design choice aligns with Python's focus on simplicity, clarity, and reducing potential confusion. In this article, we will see why Python does not include these operators and how you can achieve similar functionality using Pythonic alternatives
3 min read
Python Arithmetic Operators
Python operators are fundamental for performing mathematical calculations. Arithmetic operators are symbols used to perform mathematical operations on numerical values. Arithmetic operators include addition (+), subtraction (-), multiplication (*), division (/), and modulus (%). Addition OperatorIn Python, + is the addition operator. It is used to
4 min read
Comparison Operators in Python
Python operators can be used with various data types, including numbers, strings, boolean and more. In Python, comparison operators are used to compare the values of two operands (elements being compared). When comparing strings, the comparison is based on the alphabetical order of their characters (lexicographic order).Be cautious when comparing f
4 min read
Python Logical Operators
Python logical operators are used to combine conditional statements, allowing you to perform operations based on multiple conditions. These Python operators, alongside arithmetic operators, are special symbols used to carry out computations on values and variables. In this article, we will discuss logical operators in Python definition and also loo
6 min read
Python Bitwise Operators
Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic and logical computations. The value the operator operates on is known as the Operand. Python bitwise operators are used to perform bitwise calculations on integers. The integers are first converted into binary and then operation
6 min read
Assignment Operators in Python
The Python Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, and bitwise computations. The value the operator operates on is known as the Operand. Assignment Operators are used to assign values to variables. This operator is used to assign the value of the right side
7 min read
Python Membership and Identity Operators
There is a large set of Python operators that can be used on different datatypes. Sometimes we need to know if a value belongs to a particular set. This can be done by using the Membership and Identity Operators. In this article, we will learn about Python Membership and Identity Operators. Table of Content Python Membership OperatorsPython IN Oper
5 min read
Operators Precedence in Scala
An operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Which operator is performed first in an expression with more than one operators with different precedence is determined by operator precedence. For example, 10 + 20 * 30 is calculated as 10 + (20 *
3 min read
Boolean Operators - Django Template Tags
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variable
5 min read
G-Fact 19 (Logical and Bitwise Not Operators on Boolean)
Most of the languages including C, C++, Java, and Python provide a boolean type that can be either set to False or True. In this article, we will see about logical and bitwise not operators on boolean. Logical Not (or !) Operator in PythonIn Python, the logical not operator is used to invert the truth value of a Boolean expression, returning True i
4 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
Practice Tags :