Python Operators

17 Jun, 2022
Python Operators in general are used to perform operations on values and variables. These are standard symbols used for the purpose of logical and arithmetic operations. In this article, we will look into different types of Python operators. 
OPERATORS: Are the special symbols. Eg- + , * , /, etc.
OPERAND: It is the value on which the operator is applied.
Arithmetic operators are used to performing 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 integer was an integer and to obtain an integer result in Python 3.x floored (// integer) is used.
P – Parentheses
E – Exponentiation
M – Multiplication     (Multiplication and division have the same precedence)
D – Division
A – Addition     (Addition and subtraction have the same precedence)
S – Subtraction
The modulus operator helps us extract the last digit/s of a number. For example:
x % 10 -> yields the last digit
x % 100 -> yield last two digits
Python3
# Examples of Arithmetic Operatora = 9b = 4 # Addition of numbersadd = a + b # Subtraction of numberssub = a - b # Multiplication of numbermul = a * b # Division(float) of numberdiv1 = a / b # Division(floor) of numberdiv2 = a // b # Modulo of both numbermod = a % b # Powerp = a ** b # print resultsprint(add)print(sub)print(mul)print(div1)print(div2)print(mod)print(p)
13
5
36
2.25
2
1
6561
Note: Refer to Differences between / and // for some interesting facts about these two operators.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Comparison of Relational operators compares the values. It either returns True or False according to the condition.
= is an assignment operator and == comparison operator.
Python3
# Examples of Relational Operatorsa = 13b = 33 # a > b is Falseprint(a > b) # a < b is Trueprint(a < b) # a == b is Falseprint(a == b) # a != b is Trueprint(a != b) # a >= b is Falseprint(a >= b) # a <= b is Trueprint(a <= b)
False
True
False
True
False
True
Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used to combine conditional statements.
Python3
# Examples of Logical Operatora = Trueb = False # Print a and b is Falseprint(a and b) # Print a or b is Trueprint(a or b) # Print not a is Falseprint(not a)
False
True
False
Bitwise operators act on bits and perform the bit-by-bit operations. These are used to operate on binary numbers.
Python3
# Examples of Bitwise operatorsa = 10b = 4 # Print bitwise AND operationprint(a & b) # Print bitwise OR operationprint(a | b) # Print bitwise NOT operationprint(~a) # print bitwise XOR operationprint(a ^ b) # print bitwise right shift operationprint(a >> 2) # print bitwise left shift operationprint(a << 2)
0
14
-11
14
2
40
Assignment operators are used to assign values to the variables.
Python3
# Examples of Assignment Operatorsa = 10 # Assign valueb = aprint(b) # Add and assign valueb += aprint(b) # Subtract and assign valueb -= aprint(b) # multiply and assignb *= aprint(b) # bitwise lishift operatorb <<= aprint(b)
10
20
10
100
102400
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 
Python3
a = 10b = 20c = a print(a is not b)print(a is c)
True
True
in and not in are the membership operators; 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
Python3
# Python program to illustrate# not 'in' operatorx = 24y = 20list = [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")
x is NOT present in given list
y is present in given list
Precedence and Associativity of Operators: Operator precedence and associativity determine the priorities of the operator.
This is used in an expression with more than one operator with different precedence to determine which operation to perform first.
Python3
# Examples of Operator Precedence # Precedence of '+' & '*'expr = 10 + 20 * 30print(expr) # Precedence of 'or' & 'and'name = "Alex"age = 0 if name == "Alex" or name == "John" and age >= 2:    print("Hello! Welcome.")else:    print("Good Bye!!")
610
Hello! Welcome.
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.
Python3
# Examples of Operator Associativity # Left-right associativity# 100 / 10 * 10 is calculated as# (100 / 10) * 10 and not# as 100 / (10 * 10)print(100 / 10 * 10) # Left-right associativity# 5 - 2 + 3 is calculated as# (5 - 2) + 3 and not# as 5 - (2 + 3)print(5 - 2 + 3) # left-right associativityprint(5 - (2 + 3)) # right-left associativity# 2 ** 3 ** 2 is calculated as# 2 ** (3 ** 2) and not# as (2 ** 3) ** 2print(2 ** 3 ** 2)
100.0
6
0
512
https://youtu.be/oiJUZbRIR7Y
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: 
The quotient returns by this operator is always a float number, no matter if two numbers are integer. For example:
>>>5/5
1.0
>>>10/2
5.0
>>>-10/2
-5.0
>>>20.0/2
10.0
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:
>>>5//5
1
>>>3//2
1
>>>10//3
3
Consider the below statements in Python.
Python3
# A Python program to demonstrate the use of# "//" for integersprint (5//2)print (-5//2)
Output:
2
-3
The first output is fine, but the second one may be surprised if we are coming Java/C++ world. In Python, the “//” operator works as a floor division for integer and float arguments. However, the division operator ‘/’ returns always a float value.
Note: The “//” operator is used to return the closest integer value which is less than or equal to a specified expression or value. So from the above code, 5//2 returns 2. You know that 5/2 is 2.5, and the closest integer which is less than or equal is 2[5//2].( it is inverse to the normal maths, in normal maths the value is 3).
Example
Python3
# A Python program to demonstrate use of# "/" for floating point numbersprint (5.0/2)print (-5.0/2)
2.5
-2.5
The real floor division operator is “//”. It returns the floor value for both integer and floating-point arguments.
Python3
# A Python program to demonstrate use of# "//" for both integers and floating pointsprint (5//2)print (-5//2)print (5.0//2)print (-5.0//2)
2
-3
2.0
-3.0
See this for example. 
Python Programming Tutorial - Operators - Part 1 | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPython Programming Tutorial - Operators - Part 1 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:38•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=oiJUZbRIR7Y" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Ternary operators
Ternary operators are 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] 
Simple Method to use ternary operator:
Python
# Program to demonstrate conditional operatora, b = 10, 20 # Copy value of a in min if a < b else copy bmin = a if a < b else b print(min)
Output: 
10
Direct Method by using tuples, Dictionary, and lambda
Python
# Python program to demonstrate ternary operatora, b = 10, 20 # Use tuple for selecting an item# (if_test_false,if_test_true)[test]# if [a<b] is true it return 1, so element with 1 index will print# else if [a<b] is false it return 0, so element with 0 index will printprint( (b, a) [a < b] ) # Use Dictionary for selecting an item# if [a < b] is true then value of True key will print# else if [a<b] is false then value of False key will printprint({True: a, False: b} [a < b]) # lambda is more efficient than above two methods# because in lambda  we are assure that# only one expression will be evaluated unlike in# tuple and Dictionaryprint((lambda: b, lambda: a)[a < b]())
Output:
10
10
10
Ternary operator can be written as nested if-else:
Python
# Python program to demonstrate nested ternary operatora, b = 10, 20 print ("Both a and b are equal" if a == b else "a is greater than b"        if a > b else "b is greater than a")
The above approach can be written as:  
Python
# Python program to demonstrate nested ternary operatora, b = 10, 20 if a != b:    if a > b:        print("a is greater than b")    else:        print("b is greater than a")else:    print("Both a and b are equal")
Output:
 b is greater than a
To use print function in ternary operator be like:- 
Example: Find the Larger number among 2 using ternary operator in python3
Python3
a=5b=7 # [statement_on_True] if [condition] else [statement_on_false] print(a,"is greater") if (a>b) else print(b,"is Greater")
Output:
7 is Greater
First the given condition is evaluated (a < b), then either a or b is returned based on the Boolean value returned by the condition
Order of the arguments in the operator is different from other languages like C/C++ (See C/C++ ternary operators).
Conditional expressions have the lowest priority amongst all Python operations.
Method used prior to 2.5 when the ternary operator was not present In an expression like the one given below, the interpreter checks for the expression if this is true then on_true is evaluated, else the on_false is evaluated. 
Syntax : 
'''When condition becomes true, expression [on_false]
   is not executed and value of "True and [on_true]"
   is returned.  Else value of "False or [on_false]"
   is returned.
   Note that "True and x" is equal to x. 
   And "False or x" is equal to x. '''
[expression] and [on_true] or [on_false] 
Example : 
Python
# Program to demonstrate conditional operatora, b = 10, 20 # If a is less than b, then a is assigned# else b is assigned (Note : it doesn't# work if a is 0.min = a < b and a or b print(min)
Output:
10
Note : The only drawback of this method is that on_true must not be zero or False. If this happens on_false will be evaluated always. The reason for that is if the expression is true, the interpreter will check for the on_true, if that will be zero or false, that will force the interpreter to check for on_false to give the final result of the whole expression.
nikhilaggarwal3
ruhelaa48
sg4ipiafwot258z3lh6xa2mjq2qtxd89f49zgt7g
kushagrathegame1
aditiyadav20102001
python-basics
Python-Operators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python