Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • πŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • πŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • πŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • πŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • πŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • πŸ“ For Each Assignments
    • πŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • πŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • πŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • πŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • πŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • πŸ“ Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • πŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • πŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • πŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • πŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • πŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • πŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • πŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • πŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • πŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • πŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • πŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • πŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • πŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • πŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

πŸ“ Python Operators: Practice Assignments with Detailed Solutions

Python Operators Practice Assignments with Detailed Solutions

Practice makes perfect β€” solve these real-world assignments to master Python operators.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
πŸ“‘ On this page:
  • About These Assignments
  • Arithmetic Operators
  • Assignment Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Special Operators
  • Mixed Practice
  • Try It Yourself
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link

About These Assignments

This page contains 50+ practice assignments covering all Python operator types. Each problem is designed to:

  • Reinforce your understanding of Python operators
  • Apply concepts to real-world scenarios
  • Build problem-solving skills step by step
  • Prepare you for coding interviews
🟒 Beginner 🟠 Intermediate πŸ”΄ Advanced

πŸ’‘ Tip: Try solving each problem on your own first. Click the "Show Solution" button only after you've attempted the problem. This approach will help you learn more effectively.

1. Arithmetic Operators 10 Questions

🎯 Learning Goal: Master addition (+), subtraction (-), multiplication (*), division (/), modulus (%), floor division (//), and exponentiation (**) operators through real-world problems.
Beginner Q1: Calculate the Total Cost of Items
Scenario: You're building a shopping cart system. A customer buys 3 items priced at β‚Ή250, β‚Ή350, and β‚Ή450. Write a Python program that calculates and displays the total cost using the addition operator.
πŸ’‘ Solution:
item1 = 250
item2 = 350
item3 = 450
total = item1 + item2 + item3
print(f"Total cost: β‚Ή{total}") # Output: β‚Ή1050
πŸ“– Explanation:

We use the + operator to add all three item prices together. The result is stored in the total variable and displayed using an f-string. This is a common pattern in e-commerce applications.

Beginner Q2: Calculate the Area of a Rectangle
Scenario: You're designing a room. The length is 12 meters and the width is 8 meters. Write a program that calculates the area using the multiplication operator.
πŸ’‘ Solution:
length = 12
width = 8
area = length * width
print(f"Area: {area} square meters") # Output: 96
πŸ“– Explanation:

The multiplication operator * multiplies length and width to calculate the area. This formula is used in architecture, interior design, and real estate applications.

Beginner Q3: Find the Remainder Using Modulus
Scenario: You have 27 apples and want to divide them equally among 5 friends. Write a program that calculates how many apples each friend gets and how many are left over using the modulus operator.
πŸ’‘ Solution:
apples = 27
friends = 5
each = apples // friends # Floor division for equal share
leftover = apples % friends # Modulus for remainder
print(f"Each friend gets: {each} apples")
print(f"Apples left over: {leftover}")
# Output: Each friend gets: 5 apples
# Apples left over: 2
πŸ“– Explanation:

The floor division operator // gives the number each person gets (quotient), while the modulus operator % gives the remainder. This pattern is used in inventory management and resource allocation.

Intermediate Q4: Calculate BMI (Body Mass Index)
Scenario: You're building a health tracking app. A user weighs 70 kg and is 1.75 meters tall. Write a program that calculates their BMI using the formula: BMI = weight / heightΒ².
πŸ’‘ Solution:
weight = 70.0
height = 1.75
bmi = weight / (height ** 2)
print(f"BMI: {bmi:.2f}") # Output: 22.86
πŸ“– Explanation:

We use the exponentiation operator ** to square the height, then divide the weight by that value. The :.2f formats the output to 2 decimal places. This is used in health, fitness, and medical applications.

Intermediate Q5: Calculate Simple Interest
Scenario: You're a bank teller. A customer deposits β‚Ή10,000 at 8% annual interest for 3 years. Write a program that calculates the simple interest using the formula: SI = P Γ— R Γ— T / 100.
πŸ’‘ Solution:
principal = 10000
rate = 8
time = 3
simple_interest = (principal * rate * time) / 100
print(f"Simple Interest: β‚Ή{simple_interest:.2f}") # Output: β‚Ή2400.00
πŸ“– Explanation:

We multiply principal, rate, and time using *, then divide by 100 using /. This demonstrates how multiple arithmetic operators work together in a single expression, commonly used in banking and finance applications.

Intermediate Q6: Convert Celsius to Fahrenheit
Scenario: You're building a weather app. The temperature in Celsius is 25Β°C. Write a program that converts it to Fahrenheit using the formula: F = (C Γ— 9/5) + 32.
πŸ’‘ Solution:
celsius = 25
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}Β°C = {fahrenheit}Β°F") # Output: 25Β°C = 77.0Β°F
πŸ“– Explanation:

We use * and / to multiply by 9/5, then + to add 32. This demonstrates operator precedence β€” multiplication and division happen before addition. This is used in weather apps, scientific applications, and international travel.

Advanced Q7: Calculate Compound Interest
Scenario: You're a financial advisor. A client invests β‚Ή10,000 at 8% annual interest compounded annually for 3 years. Write a program that calculates the compound interest using the formula: CI = P Γ— (1 + R/100)^T - P.
πŸ’‘ Solution:
p = 10000
r = 8
t = 3
amount = p * (1 + r/100) ** t
compound_interest = amount - p
print(f"Compound Interest: β‚Ή{compound_interest:.2f}") # Output: β‚Ή2597.12
πŸ“– Explanation:

We use ** for exponentiation, which has higher precedence than * and /. The expression (1 + r/100) ** t calculates the growth factor. This demonstrates the power of combining multiple operators for complex financial calculations.

Advanced Q8: Calculate Distance Between Two Points
Scenario: You're building a navigation system. Point A is at coordinates (3, 4) and Point B is at (7, 1). Write a program that calculates the distance using the formula: d = √((xβ‚‚ - x₁)Β² + (yβ‚‚ - y₁)Β²).
πŸ’‘ Solution:
import math
x1, y1 = 3, 4
x2, y2 = 7, 1
distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
print(f"Distance: {distance:.2f}") # Output: 5.00
πŸ“– Explanation:

We use - for difference, ** for squaring, + for addition, and math.sqrt() for square root. This demonstrates combining arithmetic operators with built-in functions, used in GPS systems, gaming, and graphics applications.

2. Assignment Operators 6 Questions

🎯 Learning Goal: Master basic assignment (=), compound assignment (+=, -=, *=, /=, %=), and chain assignment.
Beginner Q9: Basic Variable Assignment
Scenario: You're storing user data. A user's age is 25. Write a program that assigns this value to a variable and displays it.
πŸ’‘ Solution:
age = 25
print(f"User's age: {age}") # Output: 25
πŸ“– Explanation:

The = operator assigns the value 25 to the variable age. This is the most basic and commonly used assignment operation in Python.

Beginner Q10: Addition Assignment Operator
Scenario: You're tracking a score in a game. The current score is 50. The player earns 15 bonus points. Write a program that updates the score using the += operator.
πŸ’‘ Solution:
score = 50
score += 15 # Equivalent to score = score + 15
print(f"New score: {score}") # Output: 65
πŸ“– Explanation:

The += operator adds 15 to the current value of score. This is a shorthand for score = score + 15 and is commonly used in gaming and counter applications.

Intermediate Q11: Chain Assignment
Scenario: You're initializing multiple variables with the same starting value in a game. Write a program that assigns the value 100 to three variables (health, mana, stamina) using chain assignment.
πŸ’‘ Solution:
health = mana = stamina = 100
print(f"Health: {health}, Mana: {mana}, Stamina: {stamina}")
# Output: Health: 100, Mana: 100, Stamina: 100
πŸ“– Explanation:

Chain assignment allows you to assign the same value to multiple variables in a single line. This is efficient and readable, commonly used for initializing game stats or configuration values.

3. Relational Operators 7 Questions

🎯 Learning Goal: Master comparison operators: equal to (==), not equal (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=).
Beginner Q12: Check if Two Numbers are Equal
Scenario: You're building a login system. A user enters their age as 18. The minimum age is 18. Write a program that checks if the user's age equals the minimum age using ==.
πŸ’‘ Solution:
age = 18
min_age = 18
is_equal = age == min_age
print(f"Is age equal to minimum? {is_equal}") # Output: True
πŸ“– Explanation:

The == operator compares two values for equality. It returns True if they are equal, otherwise False. This is used in authentication, validation, and conditional logic.

Intermediate Q13: Find the Maximum of Three Numbers
Scenario: You're building a grading system. Three students scored 85, 92, and 78. Write a program that finds and displays the highest score using relational operators.
πŸ’‘ Solution:
score1, score2, score3 = 85, 92, 78
max_score = score1
if score2 > max_score:
max_score = score2
if score3 > max_score:
max_score = score3
print(f"Highest score: {max_score}") # Output: 92
πŸ“– Explanation:

The > operator compares values to find the largest. We use an if statement to update the maximum when a larger value is found. This is commonly used in data analysis and ranking applications.

4. Logical Operators 8 Questions

🎯 Learning Goal: Master logical operators: AND, OR, NOT β€” combining multiple conditions.
Beginner Q14: AND Operator β€” Check if Number is in Range
Scenario: You're building a discount system. A customer gets a discount if their purchase amount is between β‚Ή500 and β‚Ή1000. Write a program that checks if the amount is in this range using and.
πŸ’‘ Solution:
amount = 750
is_eligible = amount >= 500 and amount <= 1000
print(f"Eligible for discount: {is_eligible}") # Output: True
πŸ“– Explanation:

The and operator returns True only if both conditions are True. This is used in eligibility checks, validation, and filtering applications.

Intermediate Q15: OR Operator β€” Check Divisibility
Scenario: You're building a number puzzle game. A number wins if it's divisible by 3 OR 5. Write a program that checks if a number is divisible by 3 or 5 using or.
πŸ’‘ Solution:
num = 9
is_winning = num % 3 == 0 or num % 5 == 0
print(f"Is {num} a winning number? {is_winning}") # Output: True
πŸ“– Explanation:

The or operator returns True if at least one condition is True. This is used in game logic, filtering, and decision-making systems.

5. Bitwise Operators 6 Questions

🎯 Learning Goal: Master bitwise operators: AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right shift (>>).
Intermediate Q16: Bitwise AND β€” Check Permissions
Scenario: You're building a file system. A user has READ (1) and WRITE (2) permissions (total: 3). Write a program that checks if the user has READ permission using &.
πŸ’‘ Solution:
READ = 1 # binary: 0001
WRITE = 2 # binary: 0010
EXECUTE = 4 # binary: 0100
user_permission = READ | WRITE # 3
can_read = user_permission & READ
print(f"Can read? {bool(can_read)}") # Output: True
πŸ“– Explanation:

The bitwise AND operator & checks if a specific bit is set. This is commonly used in permission systems, flag checking, and low-level programming.

Advanced Q17: Check if Number is a Power of 2
Scenario: You're building a memory allocation system. You need to check if a number is a power of 2 for efficient memory allocation. Write a program that checks if a number is a power of 2 using bitwise operators.
πŸ’‘ Solution:
n = 16
is_power = n > 0 and (n & (n - 1)) == 0
print(f"Is {n} a power of 2? {is_power}") # Output: True
πŸ“– Explanation:

A power of 2 has exactly one bit set. n & (n - 1) clears the lowest set bit. If the result is 0, the number is a power of 2. This demonstrates the power of bitwise operations in performance-critical applications.

6. Special Operators 6 Questions

🎯 Learning Goal: Master identity operators (is, is not) and membership operators (in, not in).
Beginner Q18: Check for None Using 'is'
Scenario: You're building a database query system. A query returns None if no result is found. Write a program that checks if the result is None using is.
πŸ’‘ Solution:
result = None
is_none = result is None
print(f"Is result None? {is_none}") # Output: True
πŸ“– Explanation:

The is operator checks identity, not equality. It's the preferred way to check for None because None is a singleton object. This is used in database queries, API responses, and error handling.

Intermediate Q19: Check Membership in a List
Scenario: You're building a shopping cart. You need to check if an item is already in the cart. Write a program that checks if "apple" is in the cart using in.
πŸ’‘ Solution:
cart = ["apple", "banana", "cherry"]
is_in_cart = "apple" in cart
print(f"Is 'apple' in cart? {is_in_cart}") # Output: True
πŸ“– Explanation:

The in operator checks if a value exists in a sequence (list, tuple, string, etc.). This is commonly used in shopping carts, user permissions, and data validation.

7. Mixed Practice 7 Questions

🎯 Learning Goal: Apply all operator types together in complex, real-world scenarios.
Advanced Q20: Calculate Electricity Bill
Scenario: You're building a utility billing system. The electricity bill is calculated as follows:
  • First 100 units: β‚Ή5 per unit
  • Next 100 units: β‚Ή7 per unit
  • Above 200 units: β‚Ή10 per unit
Write a program that calculates the bill for 250 units using arithmetic and relational operators.
πŸ’‘ Solution:
units = 250
if units <= 100:
bill = units * 5
elif units <= 200:
bill = 100 * 5 + (units - 100) * 7
else:
bill = 100 * 5 + 100 * 7 + (units - 200) * 10
print(f"Total bill: β‚Ή{bill}") # Output: β‚Ή1700
πŸ“– Explanation:

This problem combines relational operators (<=) for comparison, arithmetic operators (*, +, -) for calculations, and logical flow (if, elif, else) for decision-making. It's a common pattern in utility billing, tax calculation, and pricing systems.

Advanced Q21: Leap Year Check
Scenario: You're building a calendar application. A year is a leap year if:
  • It is divisible by 400, OR
  • It is divisible by 4 but NOT by 100
Write a program that checks if a year is a leap year using logical and arithmetic operators.
πŸ’‘ Solution:
year = 2024
is_leap = (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0)
print(f"Is {year} a leap year? {is_leap}") # Output: True
πŸ“– Explanation:

This problem combines the modulus operator % for divisibility checks, logical operators (or, and) for combining conditions, and relational operators (==, !=) for comparison. It's a classic interview question that tests understanding of operator combinations.

Try It Yourself!

Use the interactive editor below to test your solutions or write your own code.

Loading Pyodide... 0%
Python Code Editor
========================================
OPERATORS PRACTICE
========================================
7 is odd
Maximum: 25
Is 75 in range? True

βœ… Write your solutions here!

πŸ“š Related Tutorials

πŸ”’ Arithmetic Operators

Review arithmetic operators with examples

πŸ“Š Relational Operators

Review comparison operators with examples

🧠 Logical Operators

Review logical operators with examples

πŸ“– Related Tutorials
  • Arithmetic Operators
  • Assignment Operators
  • Relational Operators
  • Logical Operators
πŸ“– Interview & FAQ Resources
  • SQL - Displaying Data from Multiple Tables FAQ
  • SQL Window Functions & Analytic Functions FAQ
  • Python Data Types Interview Questions
  • Python Tuples and Sets Interview Questions
  • Java Basic Input/Output Interview Questions
  • Java Advanced Threads and Concurrency Interview Questions
Previous: Special Operators Next: Python Input β†’