Module 3: Operators in Python
Operators are symbols and keywords that tell Python to perform an operation on one or more values. They are fundamental to programming because they allow you to perform calculations, compare values, combine conditions, manipulate bits, check object identity, and test membership.
For example:
1a = 10 2b = 5 3 4result = a + b 5 6print(result)
Output:
115
In this example:
aandbare operands.+is an arithmetic operator.a + bis an expression.resultstores the value produced by the expression.
Understanding operators is essential before learning more advanced Python concepts such as conditional statements, loops, functions, and algorithms.
What Is an Operator?
An operator is a symbol or keyword that performs an operation on values or objects.
Consider:
110 + 5
Here:
110 → Operand 2+ → Operator 35 → Operand
The + operator tells Python to add the two operands.
Operators can work with different types of data. For example:
1print(10 + 5) 2print("Hello " + "Python")
Output:
115 2Hello Python
The behavior of an operator depends on the types of objects involved.
Types of Operators in Python
Python provides several important categories of operators:
- Arithmetic operators
- Comparison operators
- Assignment operators
- Logical operators
- Bitwise operators
- Identity operators
- Membership operators
Each category has a different purpose.
Arithmetic Operators
Arithmetic operators are used for mathematical calculations.
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 10 + 5 | 15 |
- | Subtraction | 10 - 5 | 5 |
* | Multiplication | 10 * 5 | 50 |
/ | Division | 10 / 5 | 2.0 |
// | Floor division | 10 // 3 | 3 |
% | Modulus | 10 % 3 | 1 |
** | Exponentiation | 2 ** 3 | 8 |
Addition Operator
The + operator adds numeric values.
1a = 15 2b = 5 3 4print(a + b)
Output:
120
The + operator can also concatenate strings:
1first_name = "Ankit" 2last_name = "Kushwaha" 3 4full_name = first_name + " " + last_name 5 6print(full_name)
Output:
1Ankit Kushwaha
Subtraction Operator
The - operator subtracts one number from another.
1a = 15 2b = 5 3 4print(a - b)
Output:
110
Multiplication Operator
The * operator multiplies values.
1price = 100 2quantity = 5 3 4total = price * quantity 5 6print(total)
Output:
1500
The * operator can also repeat strings:
1print("Python " * 3)
Output:
1Python Python Python
Division Operator
The / operator performs true division and returns a floating-point result.
1a = 10 2b = 4 3 4print(a / b)
Output:
12.5
Even when both operands are integers, / normally returns a float.
1print(10 / 2)
Output:
15.0
Floor Division Operator
The // operator performs floor division.
1a = 10 2b = 4 3 4print(a // b)
Output:
12
An important detail is that floor division means rounding toward negative infinity, not simply removing the decimal part.
For example:
1print(10 // 3) 2print(-10 // 3)
Output:
13 2-4
This differs from int():
1print(int(-10 / 3))
Output:
1-3
Therefore, // and int() should not be treated as interchangeable operations.
Modulus Operator
The % operator returns the remainder of a division.
1a = 17 2b = 5 3 4print(a % b)
Output:
12
The modulus operator is especially useful for determining whether a number is even or odd.
1number = 18 2 3if number % 2 == 0: 4 print("Even") 5else: 6 print("Odd")
Output:
1Even
Exponentiation Operator
The ** operator raises a number to a power.
1print(2 ** 3) 2print(5 ** 2) 3print(10 ** 3)
Output:
18 225 31000
For example:
1base = 4 2power = 3 3 4result = base ** power 5 6print(result)
Output:
164
Complete Arithmetic Example
You can combine arithmetic operators in one program.
1a = 20 2b = 6 3 4print("Addition:", a + b) 5print("Subtraction:", a - b) 6print("Multiplication:", a * b) 7print("Division:", a / b) 8print("Floor Division:", a // b) 9print("Modulus:", a % b) 10print("Exponent:", a ** 2)
Output:
1Addition: 26 2Subtraction: 14 3Multiplication: 120 4Division: 3.3333333333333335 5Floor Division: 3 6Modulus: 2 7Exponent: 400
Comparison Operators
Comparison operators compare two values and produce a Boolean result: True or False.
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
Equal To (==)
The == operator checks whether two values are equal.
1print(10 == 10) 2print(10 == 5)
Output:
1True 2False
Do not confuse == with =.
1x = 10 # Assignment 2x == 10 # Comparison
Not Equal (!=)
The != operator checks whether two values are different.
1print(10 != 5) 2print(10 != 10)
Output:
1True 2False
Greater Than (>)
1print(20 > 10) 2print(5 > 10)
Output:
1True 2False
Less Than (<)
1print(5 < 10) 2print(20 < 10)
Output:
1True 2False
Greater Than or Equal (>=)
1age = 18 2 3print(age >= 18)
Output:
1True
This is commonly used when checking minimum requirements.
Less Than or Equal (<=)
1marks = 40 2 3print(marks <= 35)
Output:
1False
Practical Comparison Example
Comparison operators are frequently used in conditional statements.
1age = 20 2 3if age >= 18: 4 print("Adult") 5else: 6 print("Minor")
Output:
1Adult
The expression age >= 18 produces True, so Python executes the first block.
Assignment Operators
Assignment operators are used to assign or update values.
| Operator | Example | Equivalent |
|---|---|---|
= | x = 5 | Assign 5 |
+= | x += 2 | x = x + 2 |
-= | x -= 2 | x = x - 2 |
*= | x *= 2 | x = x * 2 |
/= | x /= 2 | x = x / 2 |
//= | x //= 2 | x = x // 2 |
%= | x %= 2 | x = x % 2 |
**= | x **= 2 | x = x ** 2 |
Basic Assignment
1x = 10 2 3print(x)
Output:
110
Addition Assignment
1x = 10 2 3x += 5 4 5print(x)
Output:
115
This is equivalent to:
1x = x + 5
Subtraction Assignment
1x = 10 2 3x -= 3 4 5print(x)
Output:
17
Multiplication Assignment
1x = 10 2 3x *= 3 4 5print(x)
Output:
130
Division Assignment
1x = 10 2 3x /= 4 4 5print(x)
Output:
12.5
Modulus Assignment
1x = 17 2 3x %= 5 4 5print(x)
Output:
12
Exponentiation Assignment
1x = 2 2 3x **= 4 4 5print(x)
Output:
116
Logical Operators
Logical operators are used to combine or modify conditions.
Python provides three logical operators:
| Operator | Meaning |
|---|---|
and | Both conditions must be true |
or | At least one condition must be true |
not | Reverses a Boolean result |
The and Operator
The and operator requires both conditions to be true.
1age = 25 2 3result = age > 18 and age < 30 4 5print(result)
Output:
1True
If either condition is false, the result is false.
1age = 35 2 3print(age > 18 and age < 30)
Output:
1False
Practical Example
1age = 25 2has_id = True 3 4if age >= 18 and has_id: 5 print("Entry allowed") 6else: 7 print("Entry denied")
Output:
1Entry allowed
The or Operator
The or operator returns a truthy result when at least one condition is true.
1marks = 40 2 3print(marks > 80 or marks >= 40)
Output:
1True
Another example:
1day = "Saturday" 2 3if day == "Saturday" or day == "Sunday": 4 print("Weekend")
Output:
1Weekend
The not Operator
The not operator reverses the truth value.
1is_logged_in = False 2 3print(not is_logged_in)
Output:
1True
Another example:
1is_admin = True 2 3if not is_admin: 4 print("Access denied") 5else: 6 print("Admin access")
Output:
1Admin access
Logical Operators and Short-Circuit Evaluation
Python's and and or operators use short-circuit evaluation.
For example:
1age = 15 2 3if age >= 18 and expensive_check(): 4 print("Allowed")
If age >= 18 is false, Python does not need to evaluate expensive_check().
Similarly, with or:
1is_admin = True 2 3if is_admin or expensive_check(): 4 print("Access allowed")
Because is_admin is already true, Python does not need to evaluate the second expression.
This behavior is useful for writing efficient and safe conditions.
Bitwise Operators
Bitwise operators work on the binary representation of integers.
Python provides:
| Operator | Name | |
|---|---|---|
& | Bitwise AND | |
| ` | ` | Bitwise OR |
^ | Bitwise XOR | |
~ | Bitwise NOT | |
<< | Left shift | |
>> | Right shift |
Bitwise operations are useful in areas such as:
- Systems programming
- Networking
- Embedded programming
- Cryptography-related algorithms
- Permissions and flags
- Performance-sensitive integer operations
Bitwise AND (&)
The & operator compares corresponding bits.
1print(5 & 3)
Binary representation:
15 = 101 23 = 011 3 --- 4 001
001 is 1 in decimal.
Output:
11
Bitwise OR (|)
The | operator sets a bit if either corresponding bit is set.
1print(5 | 3)
Binary:
15 = 101 23 = 011 3 --- 4 111
111 equals 7.
Output:
17
Bitwise XOR (^)
XOR returns 1 when the corresponding bits are different.
1print(5 ^ 3)
Binary:
15 = 101 23 = 011 3 --- 4 110
110 equals 6.
Output:
16
Bitwise NOT (~)
The ~ operator inverts the bits of an integer.
1print(~5)
Output:
1-6
A useful identity for Python integers is:
1~x == -(x + 1)
Therefore:
1print(~5)
is equivalent to:
1print(-(5 + 1))
which produces:
1-6
Left Shift (<<)
The left-shift operator shifts bits to the left.
1print(5 << 1)
Conceptually:
15 = 101 25 << 1 = 1010
1010 is 10.
Output:
110
For non-negative integers, shifting left by one position is equivalent to multiplying by 2.
1print(5 << 2)
Output:
120
Right Shift (>>)
The right-shift operator shifts bits to the right.
1print(10 >> 1)
Conceptually:
110 = 1010 210 >> 1 = 0101
Output:
15
For non-negative integers, shifting right by one position is equivalent to floor-dividing by 2.
Identity Operators
Identity operators determine whether two expressions refer to the same object.
Python provides:
| Operator | Meaning |
|---|---|
is | Same object |
is not | Different objects |
Identity is different from equality.
==compares values.iscompares object identity.
Example
1a = [1, 2] 2b = a 3 4print(a is b)
Output:
1True
Both names refer to the same list object.
Now consider:
1a = [1, 2] 2b = [1, 2] 3 4print(a == b) 5print(a is b)
Output:
1True 2False
The lists contain equal values, but they are separate objects.
When Should You Use is?
The most common use of is is checking for None.
1result = None 2 3if result is None: 4 print("No result available")
Output:
1No result available
Use == when you want to compare values.
Use is when you want to test object identity.
Membership Operators
Membership operators check whether a value exists inside a container or sequence.
Python provides:
| Operator | Meaning |
|---|---|
in | Value exists |
not in | Value does not exist |
The in Operator
1fruits = ["Apple", "Banana", "Orange"] 2 3print("Apple" in fruits) 4print("Mango" in fruits)
Output:
1True 2False
The not in Operator
1numbers = [10, 20, 30] 2 3print(50 not in numbers) 4print(20 not in numbers)
Output:
1True 2False
Membership with Strings
The in operator can check whether one string occurs inside another string.
1text = "Python Programming" 2 3print("Python" in text) 4print("Java" in text)
Output:
1True 2False
Membership also works with dictionaries, but it checks keys by default.
1user = { 2 "name": "Ankit", 3 "age": 22 4} 5 6print("name" in user) 7print("Ankit" in user)
Output:
1True 2False
Operator Precedence
When an expression contains multiple operators, Python follows a defined precedence order.
For commonly used operators, the order from higher to lower precedence is approximately:
- Parentheses:
() - Exponentiation:
** - Unary operators:
+x,-x,~x - Multiplication, division, floor division, modulus:
*,/,//,% - Addition and subtraction:
+,- - Shifts:
<<,>> - Bitwise AND:
& - Bitwise XOR:
^ - Bitwise OR:
| - Comparisons, membership, and identity:
<,<=,>,>=,==,!=,in,not in,is,is not notandor
When in doubt, use parentheses to make your intention explicit.
Example
1result = 5 + 2 * 3 2 3print(result)
Output:
111
Multiplication happens before addition:
12 * 3 = 6 25 + 6 = 11
Using Parentheses
1result = (5 + 2) * 3 2 3print(result)
Output:
121
The parentheses force addition to happen first.
Complex Example
1result = 10 + 5 * 2 ** 2 2 3print(result)
Python evaluates:
12 ** 2 = 4 25 * 4 = 20 310 + 20 = 30
Output:
130
Expressions
An expression is a combination of values, variables, operators, function calls, or other constructs that Python evaluates to produce a result.
Examples:
110 + 20
1age >= 18
1salary * 12
1name == "Ankit"
You can store an expression's result in a variable:
1a = 15 2b = 10 3 4result = (a + b) * 2 5 6print(result)
Output:
150
Expressions are the building blocks of larger Python programs.
Operator Chaining
Python allows certain comparisons to be chained.
Instead of:
1age >= 18 and age <= 60
you can write:
1age = 25 2 3print(18 <= age <= 60)
Output:
1True
This is often easier to read.
Another example:
1score = 85 2 3if 0 <= score <= 100: 4 print("Valid score")
Output:
1Valid score
Practical Program: Simple Calculator
The following program combines arithmetic operators, user input, conditional logic, and formatted output.
1num1 = float(input("Enter first number: ")) 2num2 = float(input("Enter second number: ")) 3 4print(f"Addition: {num1 + num2}") 5print(f"Subtraction: {num1 - num2}") 6print(f"Multiplication: {num1 * num2}") 7 8if num2 != 0: 9 print(f"Division: {num1 / num2}") 10 print(f"Floor Division: {num1 // num2}") 11 print(f"Modulus: {num1 % num2}") 12else: 13 print("Division, floor division, and modulus by zero are not allowed.")
Example:
1Enter first number: 20 2Enter second number: 4 3Addition: 24.0 4Subtraction: 16.0 5Multiplication: 80.0 6Division: 5.0 7Floor Division: 5.0 8Modulus: 0.0
Notice that the program checks whether num2 is zero before performing division-related operations.
Practical Program: Age Checker
You can use comparison operators to determine whether a person meets an age requirement.
1age = int(input("Enter your age: ")) 2 3if age >= 18: 4 print("You are eligible.") 5else: 6 print("You are not eligible.")
Example:
1Enter your age: 20 2You are eligible.
Practical Program: Even or Odd
The modulus operator makes it easy to determine whether an integer is even or odd.
1number = int(input("Enter a number: ")) 2 3if number % 2 == 0: 4 print("Even number") 5else: 6 print("Odd number")
Example:
1Enter a number: 17 2Odd number
Practical Program: Largest of Two Numbers
1a = float(input("Enter first number: ")) 2b = float(input("Enter second number: ")) 3 4if a > b: 5 print(f"Largest number: {a}") 6elif b > a: 7 print(f"Largest number: {b}") 8else: 9 print("Both numbers are equal.")
This version handles all three cases:
- First number is larger
- Second number is larger
- Both numbers are equal
Practical Program: Password Check
Comparison and logical operators can be combined to validate simple input.
1username = input("Enter username: ") 2password = input("Enter password: ") 3 4if username == "admin" and password == "python123": 5 print("Login successful") 6else: 7 print("Invalid username or password")
For real applications, passwords should never be hard-coded or stored as plain text. This example is only for learning Python operators.
Practical Program: Shopping Discount
1amount = float(input("Enter purchase amount: ")) 2 3if amount >= 1000: 4 discount = amount * 0.10 5 final_amount = amount - discount 6 7 print(f"Discount: ₹{discount:.2f}") 8 print(f"Final amount: ₹{final_amount:.2f}") 9else: 10 print("No discount available.") 11 print(f"Final amount: ₹{amount:.2f}")
Example:
1Enter purchase amount: 1500 2Discount: ₹150.00 3Final amount: ₹1350.00
Common Beginner Mistakes
Confusing = and ==
Incorrect:
1if age = 18: 2 print("Age is 18")
Correct:
1if age == 18: 2 print("Age is 18")
= assigns a value, while == compares values.
Dividing by Zero
This causes an error:
1result = 10 / 0
Check the denominator before performing division when its value may be zero.
1if denominator != 0: 2 result = numerator / denominator
Using is Instead of ==
Avoid:
1name = "Python" 2 3if name is "Python": 4 print("Match")
For value comparison, use:
1if name == "Python": 2 print("Match")
Use is for identity checks, especially:
1if value is None: 2 ...
Assuming // Simply Removes Decimals
For negative numbers:
1print(-10 // 3)
Output:
1-4
Floor division moves toward negative infinity.
Forgetting Operator Precedence
Instead of relying on a complicated expression:
1result = a + b * c - d / e
use parentheses when they make the intended order clearer:
1result = a + (b * c) - (d / e)
Readable code is easier to maintain and debug.
Practice Exercises
Exercise 1: Arithmetic Calculator
Create a program that accepts two numbers and displays:
- Addition
- Subtraction
- Multiplication
- Division
- Floor division
- Modulus
- Exponentiation
Exercise 2: Even or Odd
Ask the user for an integer and determine whether it is even or odd using %.
Exercise 3: Positive, Negative, or Zero
Write a program that determines whether a number is:
- Positive
- Negative
- Zero
Exercise 4: Largest Number
Ask the user for three numbers and find the largest one.
Exercise 5: Voting Eligibility
Ask the user's age and determine whether they meet the required age of 18.
Exercise 6: Login Validation
Create a simple program that checks whether both a username and password are correct using and.
Exercise 7: Membership Test
Create a list of programming languages and check whether "Python" exists using in.
Exercise 8: Identity Test
Create two lists and demonstrate the difference between:
1==
and:
1is
Exercise 9: Bitwise Operations
Take two integers and display the results of:
1& 2| 3^
Exercise 10: Shopping Discount
Create a discount calculator:
- Purchase below ₹1,000 → no discount
- Purchase of ₹1,000 or more → 10% discount
Display the original price, discount, and final price.
Module Summary
In this module, you learned how Python operators work and how they are used to build expressions and program logic.
You learned:
- What operators are
- Operands and expressions
- Arithmetic operators
- Addition
- Subtraction
- Multiplication
- Division
- Floor division
- Modulus
- Exponentiation
- Comparison operators
- Assignment operators
- Augmented assignment
- Logical operators
- Short-circuit evaluation
- Bitwise operators
- Bitwise AND
- Bitwise OR
- Bitwise XOR
- Bitwise NOT
- Left shift
- Right shift
- Identity operators
- Membership operators
- Operator precedence
- Expressions
- Comparison chaining
- Practical Python programs
Operators are used throughout Python programming. You will use them extensively when writing conditions, loops, functions, algorithms, calculators, data-processing programs, and real-world applications.
Quiz
Question 1
Which operator is used for addition?
A. *
B. +
C. &
D. %
Answer: B. +
Question 2
What is the result of:
110 / 4
A. 2
B. 2.0
C. 2.5
D. 3
Answer: C. 2.5
Question 3
Which operator returns the remainder?
A. //
B. /
C. %
D. **
Answer: C. %
Question 4
What is the result of:
110 // 3
Answer:
13
Question 5
Which operator checks equality?
A. =
B. ==
C. !=
D. is
Answer: B. ==
Question 6
Which operator is used for logical AND?
A. &
B. and
C. &&
D. AND
Answer: B. and
Question 7
What is the difference between == and is?
Answer: == compares values, while is checks whether two references point to the same object.
Question 8
Which operator checks membership?
A. is
B. ==
C. in
D. contains
Answer: C. in
Question 9
What is the result of:
15 & 3
Answer:
11
Question 10
What is the result of:
12 ** 4
Answer:
116
What's Next?
In the next module, you will learn about Python Conditional Statements.
You will learn how to use:
ifelifelse- Nested conditions
- Multiple conditions
- Conditional expressions
- Practical decision-making programs
These concepts will allow your Python programs to make decisions based on different conditions.