PythonOperators

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

NameOperatorDescriptionExampleOutput
Addition+Adds two values5 + 38
Subtraction-Subtracts one value from another5 - 32
Multiplication*Multiplies two values5 * 315
Division/Divides one value by another5 / 22.5
Floor Division//Divides and returns the integer part5 // 22
Modulus (Remainder)%Returns the remainder5 % 21
Exponentiation**Raises one value to the power of another5 ** 225

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.

NameOperatorDescriptionExampleOutput
Equal to==Checks if values are equal5 == 5True
Not equal to!=Checks if values are not equal5 != 3True
Greater than>Checks if left is greater7 > 5True
Less than<Checks if left is smaller3 < 5True
Greater/equal>=Checks if left is greater/equal5 >= 5True
Less/equal<=Checks if left is smaller/equal3 <= 5True

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.

NameOperatorDescriptionExampleOutput
Add and assign+=Adds and assigns the resultx += 5x = x + 5
Subtract and assign-=Subtracts and assigns the resultx -= 3x = x - 3
Multiply and assign*=Multiplies and assigns the resultx *= 2x = x * 2
Divide and assign/=Divides and assigns the resultx /= 4x = x / 4
Modulus and assign%=Takes modulus and assigns the resultx %= 3x = x % 3
Floor divide and assign//=Floor divides and assigns resultx //= 2x = x // 2
Exponent and assign**=Raises to power and assigns resultx **= 3x = 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

xyx and yx or ynot x
TrueTrueTrueTrueFalse
TrueFalseFalseTrueFalse
FalseTrueFalseTrueTrue
FalseFalseFalseFalseTrue

Let’s check out the logical operators now which combine boolean expressions or values and return a boolean (True or False).

NameOperatorDescriptionExampleOutput
Logical ANDandReturns True if both are TrueTrue and FalseFalse
Logical ORorReturns True if at least one is TrueTrue or FalseTrue
Logical NOTnotReturns the opposite boolean valuenot TrueFalse

5. Membership Operator

Membership operators check if a value is a member of a sequence (like a string, list, or tuple).

NameOperatorDescriptionExampleOutput
IninReturns True if value is found'a' in 'apple'True
Not Innot inReturns 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 LevelOperatorsDescription
1 (Highest)()Parentheses
2**Exponentiation
3+x, -x, ~xUnary plus, minus, and bitwise NOT
4*, /, //, %Multiplication, division, floor division, modulus
5+, -Addition and subtraction
6==, !=, >, >=, <, <=Comparison operators
7notLogical NOT
8andLogical AND
9 (Lowest)orLogical 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:

FunctionDescriptionExampleOutput
int()Converts a value to an integerint("25")25
float()Converts a value to a floatfloat("3.14")3.14
str()Converts a value to a stringstr(42)"42"
chr()Converts an integer to its Unicode characterchr(65)"A"
bool()Converts a value to a boolean (True or False)bool(0)False
type()Returns the type of the objecttype(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)

Pyground

Play with Python!

Output: