Python 3.10+ Complete E-Book
Master Python Programming from Basics to Advanced
📖 Introduction to Python
• What is Python?
Python is a high-level, interpreted, and general-purpose programming language created by Guido van Rossum in 1991.
• Why Learn Python?
- Easy to Learn: Simple and readable syntax
- Versatile: Web development, data science, AI, automation
- Large Community: Extensive libraries and frameworks
- High Demand: Popular in industry and research
- Cross-Platform: Works on Windows, Mac, and Linux
• Python Applications
| Domain | Applications | Popular Tools/Frameworks |
|---|---|---|
| Web Development | Websites, Web Apps, APIs | Django, Flask, FastAPI |
| Data Science | Data Analysis, Visualization | Pandas, NumPy, Matplotlib |
| Machine Learning | AI Models, Deep Learning | TensorFlow, PyTorch, Scikit-learn |
| Automation | Task Automation, Testing | Selenium, PyAutoGUI, Pytest |
| Game Development | 2D Games, Simulations | Pygame, Panda3D |
• Python Program Execution Flow
⚙️ Installation & Setup
• Installing Python 3.10+
Windows:
- Download: Visit python.org and download Python 3.10+
- Install: Run installer, check "Add Python to PATH"
- Verify: Open Command Prompt and type:
python --version
Mac/Linux:
- Mac: Use Homebrew:
brew install python@3.10 - Linux: Use package manager:
sudo apt install python3.10 - Verify: Open Terminal and type:
python3 --version
• Setting Up Development Environment
| IDE/Editor | Best For | Price (₹) |
|---|---|---|
| PyCharm | Professional Development | Free (Community) / ₹16,500/year (Professional) |
| VS Code | Lightweight, General Purpose | Free |
| Jupyter Notebook | Data Science, Learning | Free |
| Sublime Text | Fast Editing | ₹6,600 (one-time) |
🔤 Python Basics
• Your First Python Program
# This is a comment
print("Hello, World!")
print("Welcome to Python Programming")
# Output:
# Hello, World!
# Welcome to Python Programming
• Python Syntax Rules
- Indentation: Uses spaces (4 spaces) instead of braces
- Case Sensitive: Variable and variable are different
- Comments: Use # for single line, ''' ''' for multi-line
- No Semicolons: Line breaks separate statements
• Variables and Naming Rules
# Valid variable names
name = "Amanuddin"
age = 25
_salary = 50000
student1 = "Mallick"
# Invalid variable names (Do NOT use)
# 1student = "Error" # Cannot start with number
# my-name = "Error" # Cannot use hyphen
# for = "Error" # Cannot use keywords
• Python Keywords
| Category | Keywords |
|---|---|
| Control Flow | if, elif, else, for, while, break, continue, pass |
| Logical | and, or, not, is, in |
| Functions | def, return, lambda, yield |
| Exception | try, except, finally, raise, assert |
| Class | class, self, super |
| Boolean | True, False, None |
📊 Data Types & Variables
• Python Data Types Overview
| Data Type | Example | Description | Mutable? |
|---|---|---|---|
| int | 42, -10, 0 | Whole numbers | No |
| float | 3.14, -0.5, 2.0 | Decimal numbers | No |
| str | "Hello", 'Python' | Text/characters | No |
| bool | True, False | Boolean values | No |
| list | [1, 2, 3] | Ordered collection | Yes |
| tuple | (1, 2, 3) | Immutable collection | No |
| dict | {"name": "John"} | Key-value pairs | Yes |
| set | {1, 2, 3} | Unique elements | Yes |
• Working with Numbers
# Integer operations
x = 10
y = 3
print(x + y) # Addition: 13
print(x - y) # Subtraction: 7
print(x * y) # Multiplication: 30
print(x / y) # Division: 3.333...
print(x // y) # Floor Division: 3
print(x % y) # Modulus: 1
print(x ** y) # Exponentiation: 1000
# Float operations
price = 299.99
tax_rate = 0.18
total = price + (price * tax_rate)
print(f"Total: ₹{total:.2f}") # Total: ₹353.99
• Working with Strings
# String operations
name = "Python Programming"
print(len(name)) # Length: 18
print(name.upper()) # PYTHON PROGRAMMING
print(name.lower()) # python programming
print(name.replace("Python", "Java")) # Java Programming
print(name.split()) # ['Python', 'Programming']
# String formatting
age = 25
salary = 50000
print(f"Age: {age}, Salary: ₹{salary}") # f-string (Python 3.6+)
print("Age: {}, Salary: ₹{}".format(age, salary)) # format method
• Type Conversion
# Converting between types
x = "123"
y = int(x) # String to integer: 123
z = float(x) # String to float: 123.0
a = 45.67
b = int(a) # Float to integer: 45
c = str(a) # Float to string: "45.67"
# Checking data type
print(type(y)) # <class 'int'>
print(isinstance(y, int)) # True
🔧 Operators
• Types of Operators
| Operator Type | Operators | Example |
|---|---|---|
| Arithmetic | +, -, *, /, //, %, ** | 5 + 3 = 8 |
| Comparison | ==, !=, >, <, >=, <= | 5 > 3 → True |
| Logical | and, or, not | True and False → False |
| Assignment | =, +=, -=, *=, /= | x += 5 |
| Identity | is, is not | x is y |
| Membership | in, not in | "a" in "abc" → True |
| Bitwise | &, |, ^, ~, <<, >> | 5 & 3 = 1 |
• Operator Precedence
• Operator Examples
# Comparison operators
age = 18
print(age >= 18) # True
print(age == 18) # True
print(age != 20) # True
# Logical operators
has_id = True
age_valid = age >= 18
can_vote = has_id and age_valid
print(can_vote) # True
# Membership operators
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("grape" not in fruits) # True
# Identity operators
x = [1, 2, 3]
y = [1, 2, 3]
z = x
print(x is z) # True (same object)
print(x is y) # False (different objects)
print(x == y) # True (same values)
🔀 Control Flow
• If-Elif-Else Statement
# Basic if-else
age = 20
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
# If-elif-else
marks = 85
if marks >= 90:
grade = "A+"
elif marks >= 80:
grade = "A"
elif marks >= 70:
grade = "B"
elif marks >= 60:
grade = "C"
else:
grade = "F"
print(f"Grade: {grade}") # Grade: A
• For Loop
# Iterating through list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Using range()
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4
# Range with start and end
for i in range(1, 6):
print(i) # Prints 1, 2, 3, 4, 5
# Range with step
for i in range(0, 10, 2):
print(i) # Prints 0, 2, 4, 6, 8
# Enumerate (index and value)
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
• While Loop
# Basic while loop
count = 0
while count < 5:
print(count)
count += 1
# While with break
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == "quit":
break
print(f"You entered: {user_input}")
# While with continue
num = 0
while num < 10:
num += 1
if num % 2 == 0:
continue # Skip even numbers
print(num) # Prints odd numbers only
• Loop Control Flow
continue? → Skip to Next Iteration
pass? → Do Nothing
• Match-Case (Python 3.10+)
# Structural pattern matching (new in Python 3.10)
def http_status(status):
match status:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Internal Server Error"
case _:
return "Unknown Status"
print(http_status(200)) # OK
print(http_status(404)) # Not Found
# Pattern matching with conditions
def process_command(command):
match command.split():
case ["quit"]:
return "Quitting..."
case ["load", filename]:
return f"Loading {filename}"
case ["save", filename]:
return f"Saving {filename}"
case _:
return "Unknown command"
⚡ Functions
• Defining Functions
# Basic function
def greet():
print("Hello, World!")
greet() # Call function
# Function with parameters
def greet_user(name):
print(f"Hello, {name}!")
greet_user("Amanuddin") # Hello, Amanuddin!
# Function with return value
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result) # 8
• Function Parameters
# Default parameters
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Hello, Guest!
greet("Mallick") # Hello, Mallick!
# Keyword arguments
def calculate_price(price, tax_rate=0.18, discount=0):
total = price + (price * tax_rate) - discount
return total
print(calculate_price(1000)) # ₹1180.00
print(calculate_price(1000, discount=100)) # ₹1080.00
# *args (variable positional arguments)
def sum_all(*numbers):
return sum(numbers)
print(sum_all(1, 2, 3, 4, 5)) # 15
# **kwargs (variable keyword arguments)
def print_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
print_info(name="Amanuddin", age=25, city="Kolkata")
• Lambda Functions
# Lambda (anonymous) functions
square = lambda x: x ** 2
print(square(5)) # 25
# Lambda with multiple arguments
multiply = lambda x, y: x * y
print(multiply(4, 5)) # 20
# Using lambda with map()
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]
# Using lambda with filter()
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # [2, 4]
• Function Scope
| Scope Type | Description | Example |
|---|---|---|
| Local | Inside function only | Variables defined in function |
| Global | Accessible everywhere | Variables defined outside functions |
| Nonlocal | Nested function scope | Variables in enclosing function |
| Built-in | Python's built-in names | print(), len(), type() |
# Global vs Local scope
x = 10 # Global variable
def modify_value():
global x # Declare we're using global x
x = 20
print(f"Inside function: {x}")
modify_value() # Inside function: 20
print(f"Outside function: {x}") # Outside function: 20
📦 Data Structures
• Lists
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
# List operations
fruits.append("orange") # Add to end
fruits.insert(1, "mango") # Insert at index
fruits.remove("banana") # Remove by value
popped = fruits.pop() # Remove and return last
fruits.sort() # Sort in place
fruits.reverse() # Reverse in place
# List slicing
print(numbers[1:4]) # [2, 3, 4]
print(numbers[:3]) # [1, 2, 3]
print(numbers[2:]) # [3, 4, 5]
print(numbers[-1]) # 5 (last element)
# List comprehension
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]
• Tuples
# Creating tuples (immutable)
coordinates = (10, 20)
person = ("Amanuddin", 25, "Kolkata")
# Tuple unpacking
name, age, city = person
print(name) # Amanuddin
# Tuples are immutable
# coordinates[0] = 15 # This will raise an error!
# Tuple methods
numbers = (1, 2, 3, 2, 2, 4)
print(numbers.count(2)) # 3
print(numbers.index(3)) # 2
• Dictionaries
# Creating dictionaries
student = {
"name": "Amanuddin Mallick",
"age": 25,
"course": "Python Programming",
"fees": 15000
}
# Accessing values
print(student["name"]) # Amanuddin Mallick
print(student.get("age")) # 25
# Adding/Modifying
student["email"] = "aman@example.com"
student["age"] = 26
# Dictionary methods
print(student.keys()) # All keys
print(student.values()) # All values
print(student.items()) # Key-value pairs
# Dictionary comprehension
squares = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Nested dictionaries
students = {
"student1": {"name": "Aman", "marks": 85},
"student2": {"name": "Mallick", "marks": 92}
}
• Sets
# Creating sets (unique elements)
numbers = {1, 2, 3, 4, 5}
fruits = {"apple", "banana", "cherry"}
# Set operations
numbers.add(6) # Add element
numbers.remove(3) # Remove element
numbers.discard(10) # Remove if exists (no error)
# Set operations
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
union = set1 | set2 # {1, 2, 3, 4, 5, 6}
intersection = set1 & set2 # {3, 4}
difference = set1 - set2 # {1, 2}
symmetric_diff = set1 ^ set2 # {1, 2, 5, 6}
• Data Structure Comparison
| Structure | Ordered | Mutable | Duplicates | Use Case |
|---|---|---|---|---|
| List | Yes | Yes | Yes | General collections |
| Tuple | Yes | No | Yes | Fixed data, coordinates |
| Dictionary | Yes (3.7+) | Yes | No (keys) | Key-value mappings |
| Set | No | Yes | No | Unique elements, math ops |
🎯 Object-Oriented Programming
• Classes and Objects
# Defining a class
class Student:
# Constructor
def __init__(self, name, age, course):
self.name = name
self.age = age
self.course = course
# Method
def display_info(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")
print(f"Course: {self.course}")
def study(self):
print(f"{self.name} is studying {self.course}")
# Creating objects
student1 = Student("Amanuddin", 25, "Python")
student2 = Student("Mallick", 24, "Java")
student1.display_info()
student1.study()
• Inheritance
# Parent class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"I am {self.name}, {self.age} years old")
# Child class
class Employee(Person):
def __init__(self, name, age, employee_id, salary):
super().__init__(name, age) # Call parent constructor
self.employee_id = employee_id
self.salary = salary
def work(self):
print(f"{self.name} is working")
def get_details(self):
print(f"ID: {self.employee_id}, Salary: ₹{self.salary}")
# Using inheritance
emp = Employee("Amanuddin", 25, "E001", 50000)
emp.introduce() # Inherited method
emp.work() # Own method
emp.get_details()
• Encapsulation
# Encapsulation with private attributes
class BankAccount:
def __init__(self, account_number, balance):
self.__account_number = account_number # Private
self.__balance = balance # Private
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"Deposited: ₹{amount}")
else:
print("Invalid amount")
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
print(f"Withdrawn: ₹{amount}")
else:
print("Insufficient balance")
def get_balance(self):
return self.__balance
account = BankAccount("123456", 10000)
account.deposit(5000)
account.withdraw(3000)
print(f"Balance: ₹{account.get_balance()}")
# print(account.__balance) # This will raise an error!
• Polymorphism
# Method overriding
class Animal:
def sound(self):
print("Animal makes a sound")
class Dog(Animal):
def sound(self):
print("Dog barks: Woof! Woof!")
class Cat(Animal):
def sound(self):
print("Cat meows: Meow!")
# Polymorphism in action
animals = [Dog(), Cat(), Animal()]
for animal in animals:
animal.sound()
# Output:
# Dog barks: Woof! Woof!
# Cat meows: Meow!
# Animal makes a sound
• OOP Concepts
| Concept | Description | Benefit |
|---|---|---|
| Encapsulation | Bundling data and methods | Data hiding, security |
| Inheritance | Deriving from parent class | Code reusability |
| Polymorphism | Same interface, different implementation | Flexibility, extensibility |
| Abstraction | Hiding complex details | Simplified interface |
📁 File Handling
• Reading Files
# Reading entire file
with open("data.txt", "r") as file:
content = file.read()
print(content)
# Reading line by line
with open("data.txt", "r") as file:
for line in file:
print(line.strip())
# Reading all lines as list
with open("data.txt", "r") as file:
lines = file.readlines()
print(lines)
• Writing Files
# Writing to file (overwrites)
with open("output.txt", "w") as file:
file.write("Hello, World!\n")
file.write("Python File Handling\n")
# Appending to file
with open("output.txt", "a") as file:
file.write("New line appended\n")
# Writing multiple lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as file:
file.writelines(lines)
• File Modes
| Mode | Description | Creates File? |
|---|---|---|
| 'r' | Read only (default) | No |
| 'w' | Write (overwrites) | Yes |
| 'a' | Append (adds to end) | Yes |
| 'r+' | Read and write | No |
| 'w+' | Write and read | Yes |
| 'rb' | Read binary | No |
| 'wb' | Write binary | Yes |
• Working with CSV Files
import csv
# Writing to CSV
data = [
["Name", "Age", "Salary"],
["Amanuddin", 25, 50000],
["Mallick", 24, 45000]
]
with open("employees.csv", "w", newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
# Reading from CSV
with open("employees.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
# Using DictReader
with open("employees.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(f"{row['Name']}: ₹{row['Salary']}")
• Working with JSON Files
import json
# Python object
student = {
"name": "Amanuddin",
"age": 25,
"courses": ["Python", "Java", "JavaScript"],
"fees": 15000
}
# Writing JSON
with open("student.json", "w") as file:
json.dump(student, file, indent=4)
# Reading JSON
with open("student.json", "r") as file:
data = json.load(file)
print(data)
print(f"Name: {data['name']}")
print(f"Fees: ₹{data['fees']}")
⚠️ Exception Handling
• Try-Except Block
# Basic exception handling
try:
num = int(input("Enter a number: "))
result = 100 / num
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid input! Please enter a number.")
# Multiple exceptions
try:
file = open("data.txt", "r")
content = file.read()
file.close()
except FileNotFoundError:
print("Error: File not found!")
except PermissionError:
print("Error: Permission denied!")
except Exception as e:
print(f"An error occurred: {e}")
• Try-Except-Else-Finally
# Complete exception handling
try:
amount = float(input("Enter amount: "))
tax = amount * 0.18
except ValueError:
print("Invalid amount!")
else:
# Executes if no exception
print(f"Tax: ₹{tax:.2f}")
finally:
# Always executes
print("Operation completed")
# File handling with finally
file = None
try:
file = open("data.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("File not found!")
finally:
if file:
file.close()
print("File closed")
• Common Exceptions
| Exception | Cause | Example |
|---|---|---|
| ValueError | Invalid value conversion | int("abc") |
| ZeroDivisionError | Division by zero | 10 / 0 |
| TypeError | Wrong type operation | "5" + 5 |
| IndexError | Invalid list index | list[10] when len=5 |
| KeyError | Invalid dictionary key | dict["missing_key"] |
| FileNotFoundError | File doesn't exist | open("missing.txt") |
| AttributeError | Invalid attribute access | obj.nonexistent_attr |
| ImportError | Module not found | import missing_module |
• Raising Exceptions
# Raising exceptions
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
if age < 18:
raise Exception("Must be 18 or older")
return True
try:
check_age(15)
except ValueError as e:
print(f"ValueError: {e}")
except Exception as e:
print(f"Exception: {e}")
# Custom exceptions
class InsufficientFundsError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError("Not enough balance")
return balance - amount
• Exception Handling Flow
📚 Modules & Packages
• Importing Modules
# Importing entire module
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
# Importing specific functions
from math import pi, sqrt
print(pi) # 3.141592653589793
print(sqrt(25)) # 5.0
# Importing with alias
import datetime as dt
now = dt.datetime.now()
print(now)
# Importing everything (not recommended)
from math import *
print(sin(0)) # 0.0
• Popular Built-in Modules
| Module | Purpose | Common Functions |
|---|---|---|
| math | Mathematical operations | sqrt(), pow(), sin(), cos(), pi |
| random | Random number generation | random(), randint(), choice() |
| datetime | Date and time operations | datetime.now(), date(), time() |
| os | Operating system interface | getcwd(), mkdir(), listdir() |
| sys | System-specific parameters | argv, exit(), path |
| json | JSON encoding/decoding | dumps(), loads(), dump(), load() |
| re | Regular expressions | search(), match(), findall() |
• Creating Your Own Module
# File: mymodule.py
def greet(name):
return f"Hello, {name}!"
def calculate_gst(amount, rate=0.18):
return amount * rate
PI = 3.14159
# File: main.py
import mymodule
print(mymodule.greet("Amanuddin"))
gst = mymodule.calculate_gst(1000)
print(f"GST: ₹{gst}")
print(mymodule.PI)
• Common Module Examples
# Random module
import random
print(random.randint(1, 100)) # Random integer
print(random.choice(["A", "B", "C"])) # Random choice
print(random.random()) # Random float [0, 1)
# Datetime module
from datetime import datetime, timedelta
now = datetime.now()
print(now.strftime("%d-%m-%Y %H:%M:%S"))
tomorrow = now + timedelta(days=1)
print(f"Tomorrow: {tomorrow}")
# OS module
import os
print(os.getcwd()) # Current directory
# os.mkdir("new_folder") # Create directory
print(os.listdir()) # List files
# Statistics module
import statistics
data = [10, 20, 30, 40, 50]
print(statistics.mean(data)) # 30.0
print(statistics.median(data)) # 30
print(statistics.stdev(data)) # Standard deviation
🆕 Python 3.10+ New Features
• Structural Pattern Matching (Match-Case)
# Python 3.10+ Match-Case statement
def process_status(status_code):
match status_code:
case 200:
return "Success"
case 404:
return "Not Found"
case 500 | 502 | 503:
return "Server Error"
case _:
return "Unknown Status"
print(process_status(200)) # Success
print(process_status(500)) # Server Error
# Pattern matching with data structures
def analyze_point(point):
match point:
case (0, 0):
return "Origin"
case (0, y):
return f"On Y-axis at {y}"
case (x, 0):
return f"On X-axis at {x}"
case (x, y):
return f"Point at ({x}, {y})"
print(analyze_point((0, 0))) # Origin
print(analyze_point((5, 0))) # On X-axis at 5
print(analyze_point((3, 4))) # Point at (3, 4)
• Better Error Messages
# Python 3.10+ provides more helpful error messages
# Before Python 3.10:
# NameError: name 'value' is not defined
# Python 3.10+:
# NameError: name 'value' is not defined. Did you mean: 'values'?
# Syntax error improvements
# Python 3.10 shows the exact location of syntax errors
# with better suggestions and context
• Union Type Operator (|)
# Python 3.10+ type hinting with | operator
def process_data(value: int | str) -> str:
if isinstance(value, int):
return f"Number: {value}"
return f"Text: {value}"
# Before Python 3.10:
# from typing import Union
# def process_data(value: Union[int, str]) -> str:
# Multiple types
def calculate(x: int | float, y: int | float) -> int | float:
return x + y
print(calculate(5, 3)) # 8
print(calculate(5.5, 2.3)) # 7.8
• Python 3.10+ Features Summary
| Feature | Description | Benefit |
|---|---|---|
| Match-Case | Structural pattern matching | Cleaner conditional logic |
| Better Errors | Improved error messages | Easier debugging |
| Union Operator | Type hints with | | Simpler type annotations |
| Parenthesized Context | Better with statement syntax | More readable code |
| Precise Line Numbers | Better tracebacks | Faster error location |
• Parenthesized Context Managers
# Python 3.10+ allows parentheses for better formatting
with (
open("file1.txt", "r") as f1,
open("file2.txt", "r") as f2,
open("output.txt", "w") as output
):
content1 = f1.read()
content2 = f2.read()
output.write(content1 + content2)
✏️ Practice Questions
• Question 1: Basic Calculator
Create a calculator program that takes two numbers and an operator (+, -, *, /) as input and performs the calculation.
def calculator():
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operator = input("Enter operator (+, -, *, /): ")
match operator:
case "+":
result = num1 + num2
case "-":
result = num1 - num2
case "*":
result = num1 * num2
case "/":
if num2 == 0:
return "Error: Cannot divide by zero"
result = num1 / num2
case _:
return "Invalid operator"
return f"Result: {result}"
except ValueError:
return "Invalid input! Please enter numbers."
print(calculator())
# Sample Output:
# Enter first number: 10
# Enter second number: 5
# Enter operator (+, -, *, /): +
# Result: 15.0
• Question 2: GST Calculator
Write a program to calculate GST on a product. Take the base price and GST rate as input, display the GST amount and total price in rupees.
def calculate_gst():
try:
base_price = float(input("Enter base price (₹): "))
gst_rate = float(input("Enter GST rate (%): "))
gst_amount = base_price * (gst_rate / 100)
total_price = base_price + gst_amount
print(f"\n--- GST CALCULATION ---")
print(f"Base Price: ₹{base_price:.2f}")
print(f"GST Rate: {gst_rate}%")
print(f"GST Amount: ₹{gst_amount:.2f}")
print(f"Total Price: ₹{total_price:.2f}")
except ValueError:
print("Error: Please enter valid numbers")
calculate_gst()
# Sample Output:
# Enter base price (₹): 1000
# Enter GST rate (%): 18
#
# --- GST CALCULATION ---
# Base Price: ₹1000.00
# GST Rate: 18.0%
# GST Amount: ₹180.00
# Total Price: ₹1180.00
• Question 3: Student Grade System
Create a program that takes marks of 5 subjects, calculates total, percentage, and assigns grade (A+: 90+, A: 80-89, B: 70-79, C: 60-69, F: Below 60)
def student_grade_system():
subjects = ["Math", "Science", "English", "History", "Computer"]
marks = []
print("Enter marks for each subject (out of 100):")
for subject in subjects:
while True:
try:
mark = float(input(f"{subject}: "))
if 0 <= mark <= 100:
marks.append(mark)
break
else:
print("Marks must be between 0 and 100")
except ValueError:
print("Please enter a valid number")
total = sum(marks)
percentage = total / len(subjects)
if percentage >= 90:
grade = "A+"
elif percentage >= 80:
grade = "A"
elif percentage >= 70:
grade = "B"
elif percentage >= 60:
grade = "C"
else:
grade = "F"
print(f"\n--- RESULT ---")
print(f"Total Marks: {total}/{len(subjects) * 100}")
print(f"Percentage: {percentage:.2f}%")
print(f"Grade: {grade}")
if grade == "F":
print("Status: FAIL")
else:
print("Status: PASS")
student_grade_system()
• Question 4: Bank Account Management
Create a BankAccount class with methods for deposit, withdraw, and check balance. Include proper error handling for insufficient funds.
class BankAccount:
def __init__(self, account_holder, initial_balance=0):
self.account_holder = account_holder
self.__balance = initial_balance
self.transactions = []
def deposit(self, amount):
if amount > 0:
self.__balance += amount
self.transactions.append(f"Deposit: +₹{amount}")
print(f"✓ Deposited ₹{amount}. New Balance: ₹{self.__balance}")
else:
print("✗ Invalid amount. Deposit must be positive.")
def withdraw(self, amount):
if amount <= 0:
print("✗ Invalid amount. Withdrawal must be positive.")
elif amount > self.__balance:
print(f"✗ Insufficient funds. Balance: ₹{self.__balance}")
else:
self.__balance -= amount
self.transactions.append(f"Withdrawal: -₹{amount}")
print(f"✓ Withdrawn ₹{amount}. New Balance: ₹{self.__balance}")
def check_balance(self):
print(f"Account Holder: {self.account_holder}")
print(f"Current Balance: ₹{self.__balance}")
return self.__balance
def transaction_history(self):
print(f"\n--- TRANSACTION HISTORY ---")
if not self.transactions:
print("No transactions yet")
for transaction in self.transactions:
print(transaction)
# Usage
account = BankAccount("Amanuddin Mallick", 10000)
account.check_balance()
account.deposit(5000)
account.withdraw(3000)
account.withdraw(15000) # Should fail
account.transaction_history()
• Question 5: List Operations
Write a program that takes a list of numbers and performs: (a) Find maximum and minimum, (b) Calculate sum and average, (c) Sort in ascending and descending order, (d) Remove duplicates
def list_operations():
# Input
numbers = [45, 23, 67, 45, 89, 23, 12, 90, 67, 34]
print(f"Original List: {numbers}")
# Maximum and Minimum
print(f"\n• Maximum: {max(numbers)}")
print(f"• Minimum: {min(numbers)}")
# Sum and Average
total = sum(numbers)
average = total / len(numbers)
print(f"\n• Sum: {total}")
print(f"• Average: {average:.2f}")
# Sorting
ascending = sorted(numbers)
descending = sorted(numbers, reverse=True)
print(f"\n• Ascending Order: {ascending}")
print(f"• Descending Order: {descending}")
# Remove Duplicates
unique_numbers = list(set(numbers))
print(f"\n• After removing duplicates: {sorted(unique_numbers)}")
print(f"• Duplicate count: {len(numbers) - len(unique_numbers)}")
# Even and Odd numbers
even = [n for n in numbers if n % 2 == 0]
odd = [n for n in numbers if n % 2 != 0]
print(f"\n• Even numbers: {even}")
print(f"• Odd numbers: {odd}")
list_operations()
# Sample Output:
# Original List: [45, 23, 67, 45, 89, 23, 12, 90, 67, 34]
#
# • Maximum: 90
# • Minimum: 12
#
# • Sum: 495
# • Average: 49.50
#
# • Ascending Order: [12, 23, 23, 34, 45, 45, 67, 67, 89, 90]
# • Descending Order: [90, 89, 67, 67, 45, 45, 34, 23, 23, 12]
#
# • After removing duplicates: [12, 23, 34, 45, 67, 89, 90]
# • Duplicate count: 3
#
# • Even numbers: [12, 90, 34]
# • Odd numbers: [45, 23, 67, 45, 89, 23, 67]
🗺️ Python Programming Mind Map
PROGRAMMING
- Syntax
- Variables
- Comments
- Keywords
- Indentation
- int, float, str
- bool, None
- Type Conversion
- Arithmetic
- Comparison
- Logical
- Assignment
- if-elif-else
- for loop
- while loop
- match-case
- def keyword
- Parameters
- Return values
- Lambda
- Lists
- Tuples
- Dictionaries
- Sets
- Classes
- Objects
- Inheritance
- Encapsulation
- Polymorphism
- Read/Write
- File Modes
- CSV Files
- JSON Files
- try-except
- finally
- raise
- Custom Exceptions
- import
- Built-in
- Custom
- Packages
