Meritshot Tutorials
- Home
- »
- Types of Operators in Python
SQL Tutorial
-
Understanding Variables in PythonUnderstanding Variables in Python
-
Types Of Operators in PythonTypes Of Operators in Python
-
How to create string ?How to create string ?
-
Data Structure in PythonData Structure in Python
-
What is a Function in PythonWhat is a Function in Python
-
Parameters and Arguments in PythonParameters and Arguments in Python
-
What is a Lambda FunctionWhat is a Lambda Function
-
What is a Regular Expression?What is a Regular Expression?
-
Introduction to Loops in PythonIntroduction to Loops in Python
-
If-else Statements in PythonIf-else Statements in Python
-
Break Statement in PythonBreak Statement in Python
-
OOPS in PythonOOPS in Python
-
Space and Time in PythonSpace and Time in Python
-
Data Type in PythonData Type in Python
-
Understanding Variables in PythonUnderstanding Variables in Python
-
Types Of Operators in PythonTypes Of Operators in Python
-
How to create string ?How to create string ?
-
Data Structure in PythonData Structure in Python
1 Operators
Now let’s learn about operators, some of the operators we already know, Like in the examples above we used ‘+’ which stands for addition. This comes under Arithmatic Operators. Similarly there are many more types of operators. Let’s look into all of them in a bit more detail.
There are three broad catagories in which operators can be divided :
- Unary Operators: In Python, these are operators that work with just one value or variable to perform a specific operation. * Binary Operators: These operators in Python need two values or variables to do their job, combining them in some way to give a result. * Operands: Variables, values, or expressions that are used with the operator to perform a specific
1.1 Types of Operators:
There are several types of operators, Let’s just try to know their names then we will look into each operator in detail.
## Arithmetic Operators:
Perform mathematical calculations.
Example:
+, -, *, /, % (modulus), ** (exponentiation), // (floor division)
#Addition
x = 1
y = 7
z = x+y print(z)
# NOTE: without print statement your answer will not be visible
8
#Multiplication
x = 3
y = 7
z = x*y print(z)
21
#Modulus
x = 10
y = 5
z = x % y
print(z)
0
The modulus operator helps us in finding the remainder of the two numbers. when 10 is divided by 5 the remainder is 0. hence, the answer is ‘0’
#Exponentiation
x = 2
y = 3
z = x**y print(z)
8
Exponentiation, In the example above we can see ‘x = 2’ and ‘y = 3’ so the answer is calculated as 2^3 which is equal to 8.
#Floor Division
x = 15
y = 2
print(x // y)
7
The floor division // rounds the result down to the nearest whole number. Like the result when ‘15’ is divided by ‘2’ comes as ‘7.5’ but the result is ‘7’.
1.2 Comparison Operators:
Compare values and return a boolean (True or False) result.
Example:
== (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to)
a = 5
b = 2
# equal to operator
print(‘a == b =’, a == b)
# not equal to operator
print(‘a != b =’, a != b)
# greater than operator
print(‘a > b =’, a > b)
# less than operator
print(‘a < b =’, a < b)
# greater than or equal to operator
print(‘a >= b =’, a >= b)
# less than or equal to operator
print(‘a <= b =’, a <= b)
a == b = False
a != b = True
a > b = True
a < b = False
a >= b = True
a <= b = False
1.3 Logical Operators:
Combine boolean values to create complex conditions.
Example:
and, or, not
* LOGICAL AND :
Here both the values should be true then only the final value will be True. x < 5 and x < 10
print(True and True)
True
x = 5
print(x>3 and x<10)
True
x = 1
y = 3
print(x==y and x>y)
#The condition is x is equal to y and x should also be greater than y, which is␣
↪not possibe hence the answer is False
False
- LOGICAL OR :
Returns True if one of the statements is true x < 5 or x < 4
print(True or False)
True
x = 5
print(x > 3 or x < 4)
True
x = 1
y = 3
print(x!=y and x>y)
#!= stands for not equal to. In this case both the conditions are not satisfied
False
- LOGICAL NOT :
Reverse the result, returns False if the result is true not(x < 5 and x < 10)
print(not True)
False
x = 5
print(not(x > 3 and x < 10))
False
x = 1
y = 3
print(x==y and x>y)
False
We took the same example before also when we were learning “and”, at that time we got the result as “True” but now the result is “False” even when the condition is satisfied. This is because the “not operator” reverses the results.
1.4 Assignment Operators:
Assign values to variables.
Example: ==, +=, -=, *=, /=, %=, **=
- Assignment Operator (=) a = 7
- Addition Assignment (+=) a += 1
aka: a = a + 1
- Subtraction Assignment (-=) a -= 3
aka: a = a – 3
- Multiplication Assignment (=) a = 4
aka: a = a * 4
- Division Assignment (/=) a /= 3
aka: a = a / 3
- Remainder Assignment (%=) a %= 10
a = a % 10
- Exponent Assignment (=) a = 10
aka: a = a ** 10
1.5 Bitwise Operators:
Perform operations on individual bits of numbers. These operators are used to compare binary numbers.
Examples: &, |, ^, ~, <<, >>
There are several types of operators and each performing a different type of bitwise manipulation
Bitwise AND (‘&’)
The bitwise AND operator compares each bit of the two operands. If both bits are 1, the corresponding bit in the result is set to 1. Otherwise, it’s set to 0.
For example, 2 is 10 in binary, and 7 is 111
a = 5 # In binary: 0101
b = 3 # In binary: 0011
result = a & b # Result: 0001 (binary), which is 1 in decimal
print(result) # Output: 1
1
Bitwise OR (|)
The bitwise OR operator compares each bit of the two operands.
If at least one of the bits is 1, the corresponding bit in the result is set to 1.
a = 5 # In binary: 0101
b = 3 # In binary: 0011
result = a | b # Result: 0111 (binary), which is 7 in decimal
print(result) # Output: 7
7
Bitwise XOR (^)
The bitwise XOR operator compares each bit of the two operands. If the bits are different, the corresponding bit in the result is set to 1. If the bits are the same, the bit is set to 0.
a = 5 # In binary: 0101
b = 3 # In binary: 0011
result = a ^ b # Result: 0110 (binary), which is 6 in decimal
print(result) # Output: 6
6
Bitwise NOT (~)
The bitwise NOT operator inverts all the bits of the operand. This is also known as the bitwise complement. The result is equal to -(n + 1) where n is the original number
a = 5 # In binary: 0101
result = ~a # Result: 1010 (binary), which is -6 in decimal (2’s complement)
print(result) # Output: -6
-6
Bitwise Left Shift (<<)
The bitwise left shift operator shifts the bits of the number to the left by the specified number of positions. Each shift to the left effectively multiplies the number by 2.
a = 5 # In binary: 0101
result = a << 1 # Result: 1010 (binary), which is 10 in decimal
print(result) # Output: 10
10
Bitwise Right Shift (>>)
The bitwise right shift operator shifts the bits of the number to the right by the specified number of positions. Each shift to the right effectively divides the number by 2.
a = 5 # In binary: 0101
result = a >> 1 # Result: 0010 (binary), which is 2 in decimal
print(result) # Output: 2
2
1.6 Identity Operators:
In Python, is and is not are used to check if two values are located at the same memory location.
* is :
Returns True if both variables are the same object and false otherwise.
x = [“apple”, “banana”]
y = [“apple”, “banana”] z = x
print(x is z)
# returns True because z is the same object as x
print(x is y)
# returns False because x is not the same object as y, even if they have the␣
↪same content
print(x == y)
# to demonstrate the difference betweeen “is” and “==”: this comparison returns␣
↪True because x is equal to y
True
False
True
is not :
Returns True if both variables are not the same object and false otherwise.
x = [“apple”, “banana”]
y = [“apple”, “banana”] z = x
print(x is not z)
# returns False because z is the same object as x
print(x is not y)
# returns True because x is not the same object as y, even if they have the␣
↪same content
print(x != y)
# to demonstrate the difference betweeen “is not” and “!=”: this comparison␣
↪returns False because x is equal to y
False
True
False
1.7 Membership Operators
Membership operators in Python are used to test whether a value or variable is found within a sequence, such as a string, list, tuple, or dictionary. These operators are particularly useful for checking the presence or absence of an element within a collection.
in operator
If the value is found, it returns True; otherwise, it returns False.
message = “Hello, world!”
print(‘Hello’ in message) # Output is True
print(‘bye’ in message) # Output is False
True
False
not in operator
Evaluates to True if the specified value is not present in the sequence.
#list of numbers
numbers = [1, 2, 3, 4, 5]
print(6 not in numbers) # Output is True because 6 is not in the list
print(3 not in numbers) # Output is False because 3 is in the list
True
False
2 Operator precedence
Operator precedence is like a set of rules that tells Python the order in which to handle different parts of a calculation. Think of it as a way to make sure that when you write an expression, Python knows exactly how to break it down and solve it correctly. By following these rules, Python ensures that complex expressions give the right results, just as we expect.
The order of precedence is as follows : 1. Parentheses (): Change the order of precedence. 2. Exponentiation : (e.g., 2 3 evaluates to 8) 3. Unary Plus and Minus +x, -x: Unary operations on a single value. 4. Multiplication, Division, Floor Division, and Modulus *, /, //, %: Arithmetic operations. 5. Addition and Subtraction +, -: Arithmetic operations. 6. Bitwise Shift Operators
<<, >>: Bitwise shifting operations. 7. Bitwise AND &: Bitwise operations. 8. Bitwise XOR ^: Bitwise operations. 9. Bitwise OR |: Bitwise operations. 10. Comparison Operators ==, !=, >, <,
>=, <=: Comparison operations. 11. Identity Operators is, is not: Object identity comparisons.
- Membership Operators in, not in: Membership tests. 13. Logical NOT not: Logical negation.
14. Logical AND and: Logical conjunction. 15. Logical OR or: Logical disjunction. 16. Conditional Expressions if-else: Ternary conditional expressions
result = 2 + 3 * 4 print(result)
14
This is a simple yet powerful example to understand order of precedence. The answer is 14. If you have the knowledge of BODMAS or PEDMAS then it will be easier to understand.
Here the answer is 14 not 20. If we first add 2+3 = 5 and then 54 = 20 but this wrong. The correct way is to evaluate 34 = 12 then 12+2 = 14.
I think now it is quiet evident that how important precedence of operator is.