OPERATORS IN PYTHON
Operator is a character or a symbol that represents a specific mathematical or logical action or process. Operators are used to perform operations on variables and values. For example: *
returns product when applied on two numbers and >
tells us which value is greater. In Python, we have different types of operators. Let us discuss them in detail.
Types of Operators
1. Arithmetic Operators
Arithmetical Operators are use to perform mathematical operations and returns calculated result. These operators work with numeric data type and math’s rule BODMAS is also applied here.
Arithmetic Operators Table
Name | Operator | Description | Example | Output |
---|---|---|---|---|
Addition | + | Adds two values | 5 + 3 | 8 |
Subtraction | - | Subtracts one value from another | 5 - 3 | 2 |
Multiplication | * | Multiplies two values | 5 * 3 | 15 |
Division | / | Divides one value by another | 5 / 2 | 2.5 |
Floor Division | // | Divides and returns the integer part | 5 // 2 | 2 |
Modulus (Remainder) | % | Returns the remainder | 5 % 2 | 1 |
Exponentiation | ** | Raises one value to the power of another | 5 ** 2 | 25 |
Example
Here’s how you can use arithmetic operators in Python:
# Arithmetic Operators Usage
a = 10
b = 3
# Addition
print("Addition:", a + b) # Output: 13
# Subtraction
print("Subtraction:", a - b) # Output: 7
# Multiplication
print("Multiplication:", a * b) # Output: 30
# Division
print("Division:", a / b) # Output: 3.333...
# Floor Division
print("Floor Division:", a // b) # Output: 3
# Modulus
print("Modulus:", a % b) # Output: 1
# Exponentiation
print("Exponentiation:", a ** b) # Output: 1000
2. Relational Operators
Relational Operators are used to determine the relation between the two values. They are also called comparison operators and returns True if the comparison is true otherwise returns False if the comparison is false. Relational Operators will always return a boolean value i.e. True or False.
Name | Operator | Description | Example | Output |
---|---|---|---|---|
Equal to | == | Checks if values are equal | 5 == 5 | True |
Not equal to | != | Checks if values are not equal | 5 != 3 | True |
Greater than | > | Checks if left is greater | 7 > 5 | True |
Less than | < | Checks if left is smaller | 3 < 5 | True |
Greater/equal | >= | Checks if left is greater/equal | 5 >= 5 | True |
Less/equal | <= | Checks if left is smaller/equal | 3 <= 5 | True |
3. Augmented Assignment Operators
Augmented assignment operators are the combination of assignment (=) operator with arithmetic operators (+ - * / % // **). For example: x=x+5, can be written as x+=5.
Let us read all examples assuming value of variable x as 5.
Name | Operator | Description | Example | Output |
---|---|---|---|---|
Add and assign | += | Adds and assigns the result | x += 5 | x = x + 5 |
Subtract and assign | -= | Subtracts and assigns the result | x -= 3 | x = x - 3 |
Multiply and assign | *= | Multiplies and assigns the result | x *= 2 | x = x * 2 |
Divide and assign | /= | Divides and assigns the result | x /= 4 | x = x / 4 |
Modulus and assign | %= | Takes modulus and assigns the result | x %= 3 | x = x % 3 |
Floor divide and assign | //= | Floor divides and assigns result | x //= 2 | x = x // 2 |
Exponent and assign | **= | Raises to power and assigns result | x **= 3 | x = x ** 3 |
4. Logical Operators
Logical Operators are basically used to connect two or more expressions with relational operators. These operators are used to create complex Boolean expressions. and, or, not are three logical operators offered by Python.
Before, we start with the examples here, we need to understand Truth Value Testing. It is a common way to show logical relationships between the expressions. Assuming x and y as expressions, see how logical operators work with them.
Truth Table for Logical Operators
x | y | x and y | x or y | not x |
---|---|---|---|---|
True | True | True | True | False |
True | False | False | True | False |
False | True | False | True | True |
False | False | False | False | True |
Let’s check out the logical operators now which combine boolean expressions or values and return a boolean (True
or False
).
Name | Operator | Description | Example | Output |
---|---|---|---|---|
Logical AND | and | Returns True if both are True | True and False | False |
Logical OR | or | Returns True if at least one is True | True or False | True |
Logical NOT | not | Returns the opposite boolean value | not True | False |
5. Membership Operator
Membership operators check if a value is a member of a sequence (like a string, list, or tuple).
Name | Operator | Description | Example | Output |
---|---|---|---|---|
In | in | Returns True if value is found | 'a' in 'apple' | True |
Not In | not in | Returns True if value is not found | 'x' not in 'apple' | True |
Operator Precedence
When multiple operators are used together in an expression, Python determines the order of evaluation based on operator precedence. This ensures that expressions are evaluated correctly.
Understanding Precedence
You may already know the rule BODMAS (Brackets, Order, Division/Multiplication, Addition/Subtraction), which applies to arithmetic operations. However, Python includes many other operators, each with its own precedence.
Consider the following example:
Example
# Expression to evaluate
result = 17 > 8 + 2**4 and 9 // 2 >= 4
# Step-by-step solution:
# 1. Exponentiation (**): 2**4 → 16
# 2. Addition (+): 8 + 16 → 24
# 3. Relational (>): 17 > 24 → False
# 4. Floor Division (//): 9 // 2 → 4
# 5. Relational (>=): 4 >= 4 → True
# 6. Logical (and): False and True → False
print(result) # Output: False
The following table shows the order of precedence for Python operators, from highest to lowest:
Precedence Level | Operators | Description |
---|---|---|
1 (Highest) | () | Parentheses |
2 | ** | Exponentiation |
3 | +x, -x, ~x | Unary plus, minus, and bitwise NOT |
4 | *, /, //, % | Multiplication, division, floor division, modulus |
5 | +, - | Addition and subtraction |
6 | ==, !=, >, >=, <, <= | Comparison operators |
7 | not | Logical NOT |
8 | and | Logical AND |
9 (Lowest) | or | Logical OR |
Practice Problem: Operator Precedence
Try evaluating the following expression step by step:
result = (3 + 5) * 2 > 10 or not (5 % 2 == 0)
print(result) # What will this output?
Show Code
# Step-by-step solution:
# 1. Parentheses (): (3 + 5) → 8
# 2. Multiplication (*): 8 * 2 → 16
# 3. Relational (>): 16 > 10 → True
# 4. Parentheses (): (5 % 2) → 1, (1 == 0) → False
# 5. Logical NOT (not): not False → True
# 6. Logical OR (or): True or True → True
result = (3 + 5) * 2 > 10 or not (5 % 2 == 0)
print(result) # Output: True
Data Type Conversions
In Python, when an expression involves mixed data types, the interpreter automatically converts one data type to another to avoid data loss. This is known as implicit conversion.
Implicit Conversion
Implicit conversion happens automatically without requiring user intervention. Python promotes a data type to a higher type in mixed operations to prevent data loss.
Example:
# Implicit Conversion Example
result = 8.5 + 2 # Adding a float and an int
print(result) # Output: 10.5
# Here, Python converts 2 to 2.0 (float) to match the higher precision.
Explicit Type Conversion (Type Casting)
Explicit conversion, or type casting, is a user-defined process where specific conversion functions are used to change the type of a value to a desired format.
Common Conversion Functions:
Function | Description | Example | Output |
---|---|---|---|
int() | Converts a value to an integer | int("25") | 25 |
float() | Converts a value to a float | float("3.14") | 3.14 |
str() | Converts a value to a string | str(42) | "42" |
chr() | Converts an integer to its Unicode character | chr(65) | "A" |
bool() | Converts a value to a boolean (True or False ) | bool(0) | False |
type() | Returns the type of the object | type(42) | <class 'int'> |
Example Usage
Here’s a program demonstrating explicit type conversion:
# Explicit Type Conversion Example
# Converting string to integer
age = "25"
age = int(age) # Now age is an integer
print(f"Age: {age}, Type: {type(age)}") # Output: Age: 25, Type: <class 'int'>
# Converting float to string
pi = 3.14
pi_str = str(pi)
print(f"Pi: {pi_str}, Type: {type(pi_str)}") # Output: Pi: 3.14, Type: <class 'str'>
# Converting integer to Unicode character
char = chr(65)
print(f"Character: {char}") # Output: Character: A
# Converting integer to boolean
is_zero = bool(0)
is_one = bool(1)
print(f"0 as boolean: {is_zero}, 1 as boolean: {is_one}") # Output: 0 as boolean: False, 1 as boolean: True
Try It Yourself
Problem 1: Input height in feet and convert into cm.
Formula : cm= value in feet * 30.48
Show Code
# Solution Example:
height=float(input("Enter your Height (in feet) "))
cm=height*30.48
print(height,"ft converted into cm is",cm)
Problem 2: Input a two digit number and display sum of its digits.
For example: 25 should return 2+5=7
Show Code
# Solution Example:
num=int(input("Enter a two digit number"))
a=num%10 # % will return remainder means last digit
b=num//10 # // will return digit at tens place
print("Sum of both digits=",a+b)