Chapter 3: Operators and Expressions
3.1 Introduction
Operators are an essential part of Python programming. They allow us to perform calculations, compare values, combine conditions, and manipulate data.
For example:
a = 10 b = 5 print(a + b)
Here, + is an operator, while a + b is an expression.
In this chapter, you will learn about:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Operator precedence
Expressions
3.2 What is an Operator?
An operator is a symbol or keyword that tells Python to perform a particular operation.
Example:
x = 20 y = 10 result = x - y print(result)
Output:
10
Here:
x and y are operands.
- is the operator.
x - y is an expression.
3.3 What is an Expression?
An expression is a combination of values, variables, operators, and sometimes function calls that Python can evaluate to produce a result.
Examples:
10 + 5 price * quantity age >= 18 marks + bonus
Expressions can produce different types of results, such as numbers or Boolean values.
3.4 Arithmetic Operators
Arithmetic operators are used to perform mathematical calculations.
| Operator | Name | Example |
|---|---|---|
| + | Addition | 10 + 3 |
| - | Subtraction | 10 - 3 |
| * | Multiplication | 10 * 3 |
| / | Division | 10 / 3 |
| // | Floor Division | 10 // 3 |
| % | Modulus | 10 % 3 |
| ** | Exponentiation | 10 ** 3 |
3.5 Addition
The + operator adds values.
a = 15 b = 25 result = a + b print(result)
Output:
40
The + operator can also join strings:
first_name = "Aman" last_name = "Kumar" full_name = first_name + " " + last_name print(full_name)
Output:
Aman Kumar
3.6 Subtraction
The - operator subtracts one value from another.
total = 100 spent = 35 remaining = total - spent print(remaining)
Output:
65
3.7 Multiplication
The * operator performs multiplication.
price = 50 quantity = 4 total = price * quantity print(total)
Output:
200
The multiplication operator can also repeat strings:
print("Python " * 3)
Output:
Python Python Python
3.8 Division
The / operator performs division.
a = 20 b = 4 result = a / b print(result)
Output:
5.0
Notice that / generally produces a floating-point result.
3.9 Floor Division
The // operator performs floor division.
result = 17 // 5 print(result)
Output:
3
Floor division gives the floor of the mathematical division result.
It is useful when you need a whole-number quotient.
3.10 Modulus Operator
The % operator returns the remainder after division.
result = 17 % 5 print(result)
Output:
2
Because:
17 ÷ 5 = 3 remainder 2
The modulus operator is commonly used to determine whether a number is even or odd.
Example:
number = 24 print(number % 2)
Output:
0
If the remainder is 0, the number is divisible by 2.
3.11 Exponentiation
The ** operator is used for powers.
result = 2 ** 5 print(result)
Output:
32
This means:
2 × 2 × 2 × 2 × 2 = 32
3.12 Assignment Operator
The = operator assigns a value to a variable.
name = "Ravi" age = 21
Python also provides compound assignment operators.
| Operator | Example | Equivalent |
|---|---|---|
| = | x = 10 | x = 10 |
| += | x += 5 | x = x + 5 |
| -= | x -= 5 | x = x - 5 |
| *= | x *= 5 | x = x * 5 |
| /= | x /= 5 | x = x / 5 |
| //= | x //= 5 | x = x // 5 |
| %= | x %= 5 | x = x % 5 |
| **= | x **= 5 | x = x ** 5 |
3.13 Compound Assignment
Example:
score = 50 score += 10 print(score)
Output:
60
The statement:
score += 10
is equivalent to:
score = score + 10
Another example:
price = 100 price *= 2 print(price)
Output:
200
3.14 Comparison Operators
Comparison operators compare two values.
The result of a comparison is usually a Boolean value:
True
or:
False
| Operator | Meaning |
|---|---|
| == | Equal to |
| != | Not equal to |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal to |
| <= | Less than or equal to |
3.15 Equal To
The == operator checks whether two values are equal.
a = 10 b = 10 print(a == b)
Output:
True
Important: = and == have different purposes.
x = 10
assigns a value.
x == 10
checks whether the value is equal to 10.
3.16 Not Equal To
The != operator checks whether two values are different.
a = 10 b = 20 print(a != b)
Output:
True
3.17 Greater Than
The > operator checks whether the left value is greater than the right value.
age = 25 print(age > 18)
Output:
True
3.18 Less Than
The < operator checks whether the left value is smaller than the right value.
marks = 35 print(marks < 40)
Output:
True
3.19 Greater Than or Equal To
The >= operator checks whether a value is greater than or equal to another value.
age = 18 print(age >= 18)
Output:
True
3.20 Less Than or Equal To
The <= operator checks whether a value is less than or equal to another value.
marks = 40 print(marks <= 40)
Output:
True
3.21 Logical Operators
Logical operators are used to combine or modify conditions.
Python provides three main logical operators:
and
or
not
3.22 and Operator
The and operator returns True when both conditions are true.
age = 25 has_id = True print(age >= 18 and has_id)
Output:
True
If either condition is false, the complete and expression does not evaluate to True.
Example
age = 16 has_id = True print(age >= 18 and has_id)
Output:
False
3.23 or Operator
The or operator produces a true result when at least one condition is true.
is_student = True is_teacher = False print(is_student or is_teacher)
Output:
True
3.24 not Operator
The not operator reverses a Boolean result.
logged_in = True print(not logged_in)
Output:
False
Another example:
is_closed = False print(not is_closed)
Output:
True
3.25 Identity Operators
Identity operators compare whether two references refer to the same object.
Python provides:
is
is not
Example:
a = None print(a is None)
Output:
True
Identity comparison is different from equality comparison.
== compares values.
is checks object identity.
For beginners, is is especially useful when checking for None.
3.26 Membership Operators
Membership operators check whether a value exists inside a collection or sequence.
Python provides:
in
not in
Example:
fruits = ["apple", "banana", "mango"] print("mango" in fruits)
Output:
True
Another example:
fruits = ["apple", "banana", "mango"] print("orange" not in fruits)
Output:
True
Membership testing is useful when working with strings, lists, sets, dictionaries, and other collections.
3.27 Bitwise Operators
Bitwise operators work with the binary representation of integers.
Common bitwise operators include:
| Operator | Meaning |
|---|---|
| & | Bitwise AND |
| ` | ` |
| ^ | Bitwise XOR |
| ~ | Bitwise NOT |
| << | Left Shift |
| >> | Right Shift |
Example:
a = 6 b = 3 print(a & b)
Bitwise operations are useful in areas such as low-level programming, data processing, networking, and specialized algorithms.
They will be explored in greater detail later.
3.28 Operator Precedence
When an expression contains multiple operators, Python follows rules that determine which operation is performed first.
For example:
result = 10 + 5 * 2 print(result)
Output:
20
Multiplication is performed before addition:
5 × 2 = 10 10 + 10 = 20
3.29 Using Parentheses
Parentheses can be used to control the order of operations.
result = (10 + 5) * 2 print(result)
Output:
30
Here, the addition is performed first.
Using parentheses can also make complicated expressions easier to understand.
3.30 Basic Precedence Order
A simplified order from higher to lower precedence is:
Parentheses
Exponentiation
Multiplication, division, floor division, modulus
Addition and subtraction
Comparison operators
not
and
or
When an expression becomes complicated, using parentheses is often the clearest approach.
3.31 Example: Shopping Bill
Let's combine several operators in one program.
price = float(input("Enter price: ")) quantity = int(input("Enter quantity: ")) subtotal = price * quantity discount = subtotal * 0.10 final_amount = subtotal - discount print("Subtotal:", subtotal) print("Discount:", discount) print("Final amount:", final_amount)
This example uses:
Assignment
Multiplication
Subtraction
Variables
User input
Floating-point numbers
3.32 Example: Even or Odd Number
The modulus operator can be used to determine whether a number is even or odd.
number = int(input("Enter a number: ")) if number % 2 == 0: print("Even number") else: print("Odd number")
The if and else statements will be studied in detail in the next chapter.
The important idea here is:
number % 2
returns the remainder after division by 2.
3.33 Example: Eligibility Check
Comparison and logical operators can be combined to create conditions.
age = int(input("Enter your age: ")) has_permission = input("Do you have permission? ") print(age >= 18 and has_permission == "yes")
The expression combines:
>=
and
==
This demonstrates how operators can work together.
3.34 Common Mistakes
Mistake 1: Confusing = and ==
Incorrect:
if age = 18: print("Age is 18")
The assignment operator should not be used for comparison.
Correct:
if age == 18: print("Age is 18")
Mistake 2: Forgetting operator precedence
Consider:
result = 10 + 2 * 5
The result is:
20
not:
60
Use parentheses when you want a different order:
result = (10 + 2) * 5
Mistake 3: Using is when value comparison is intended
For ordinary value comparison, use:
a == b
rather than relying on:
a is b
The two operators have different purposes.
3.35 Mini Project: Simple Calculator
The following program performs basic arithmetic operations.
first = float(input("Enter first number: ")) second = float(input("Enter second number: ")) print("Addition:", first + second) print("Subtraction:", first - second) print("Multiplication:", first * second) if second != 0: print("Division:", first / second) else: print("Division is not possible by zero.")
This program demonstrates several concepts from the chapter.
Chapter 3 Summary
In this chapter, you learned:
What operators are
What expressions are
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Operator precedence
Parentheses in expressions
Practical use of operators in programs
Quick Revision Questions
1. What is an operator?
An operator is a symbol or keyword used to perform an operation.
2. Which operator is used for addition?
+
3. Which operator returns the remainder?
%
4. Which operator performs floor division?
//
5. Which operator is used for exponentiation?
**
6. What is the difference between = and ==?
= assigns a value, while == compares two values.
7. What are the three logical operators in Python?
and, or, and not.
8. Which operator checks membership?
in and not in.
9. Which operator checks object identity?
is and is not.
10. Why are parentheses useful in expressions?
They can control the order in which operations are evaluated and improve readability.
Practice Exercises
Exercise 1: Calculator
Write a program that accepts two numbers and displays:
Addition
Subtraction
Multiplication
Division
Remainder
Power
Exercise 2: Even or Odd
Accept an integer and determine whether it is even or odd.
Exercise 3: Comparison
Accept two numbers and display the results of:
Equal
Not equal
Greater than
Less than
Exercise 4: Shopping Calculation
Accept:
Item price
Quantity
Discount percentage
Calculate the final price.
Exercise 5: Age Check
Accept a person's age and create an expression that checks whether the person is at least 18 years old.
Exercise 6: Membership
Create a list of five fruits and check whether "apple" exists in the list.
Chapter Activity
Create a Student Result Calculator.
Your program should:
Accept marks for five subjects.
Calculate total marks.
Calculate average marks.
Calculate percentage.
Check whether the student has passed based on a rule you define.
Display the results clearly.
Try to use arithmetic, comparison, and logical operators in your solution.
Next Chapter: Conditional Statements – if, elif, and else