Python Inheritance

Inheritance Definition

Inheritance allows a class (child) to acquire properties and methods of another class (parent).

This promotes:

  • Code reusability
  • Hierarchy / structure
  • Cleaner and scalable programs

Explanation

  • Animal is the parent/base class.
  • Dog is the child/derived class.
  • Dog gets the speak() method without writing it again.

📝 Child gets access to both:
➡ show() (from Parent)
➡ display() (its own)


📝 Chain of inheritance: A → B → C
Class C inherits everything.


📝 Child receives methods of both parents.


📝 One parent → Multiple children.


📝 super() is used to call parent methods/constructors.

Python Generators

Python Generators Introduction

A Generator in Python is a special type of function that yields values one at a time, instead of returning them all at once.

Generators are memory-efficient and used for working with large datasets, streams, or infinite sequences.


Why Generators?

FeatureWhy it matters
Lazy evaluationValues are produced on demand, not all at once
Memory efficientDoesn’t store entire data in memory
Improves performanceFaster for large datasets / loops
Infinite sequencesPossible to generate endless values

Regular Function vs Generator

Normal Function

Generator Function

The keyword yield makes it a generator.


How to Use a Generator


Generator with Loop


Difference Between return and yield

KeywordBehavior
returnExits function and sends a single value
yieldPauses function, saves state, returns value, resumes on next call

Generator Expression

List comprehension

Generator expression


Practical Examples





Python Decorators

Decorator Definition

A decorator in Python is a function that modifies the behavior of another function, without changing its code.

Think of a decorator as adding a layer of functionality before and/or after the original function runs.


Why Use Decorators?

PurposeExample Use Case
Add functionality without editing original codeLogging, Authorization
Reuse common logicValidation
Track performanceExecution time calculator
Restrict accessAdmin/user roles

Basic Decorator Structure


Applying a Decorator

The @decorator_function applies extra behavior to the display() function.


Basic Example

Output:


Decorator With Arguments


Decorator Returning a Value


Real-World Example – Logging



Authentication / Access Control


Decorators with Parameters (Advanced)

Sometimes we need the decorator to accept its own argument:

Output


Nesting Multiple Decorators

Python OS Module

Introduction

The os module in Python provides functions to interact with the operating system. It allows you to work with files, folders, system paths, and environment variables and execute system commands.


Task you want to doos Module Feature
Get current directoryos.getcwd()
Change directoryos.chdir()
Create/Remove foldersos.mkdir() / os.rmdir()
List files and foldersos.listdir()
Work with environment variablesos.environ
Join file paths safelyos.path.join()
Delete a fileos.remove()
Run system commandsos.system()

Importing OS Module


Directory Operations

Get the current working directory


Create and Delete Directories

Create a new folder

Remove a folder (only if empty)

Create multiple nested directories

Remove nested directories


File Handling

Delete a file

Rename a file


Path Operations (os.path)

FunctionDescription
os.path.join()Safely join folder and file names
os.path.exists()Check if path/file exists
os.path.isdir()Check if the path is file
os.path.isfile()Check if the path is a file
os.path.getsize()Get file size in bytes

Example


Environment Variables

View environment variables

Fetch a specific variable


Run System Commands

Open Command Prompt / Terminal command


Examples of Python OS Module






os doesn’t have copy directly, so use system command



Check File Permissions




Python List MCQs

Python List MCQ Quiz (Random 10 Questions)

Python String MCQs

Python String Quiz (Random 10 of 50)

🔄 Refresh the page to get a new set of questions.

⏳ Time Left: 120 seconds

Python Read/Write CSV

What is a CSV File?

CSV stands for Comma-Separated Values and is commonly used for tabular data like spreadsheets.

Python has a built-in csv module for handling CSV files.


Write to CSV File

Write Rows Manually


Write Multiple Rows (Loop / List)


Read CSV File

Read and Print Entire File


Read CSV as Dictionary

đź’ˇ Best when the first row contains headers.


Write CSV Using Dictionary


Append to a CSV File


Handling Custom Delimiters

Example: Semi-colon ; separated file


Real Example: CSV Filtering

Print only rows where Age > 25


Summary

TaskMethod
Write rowwriter.writerow()
Write multiple rowswriter.writerows()
Read CSVcsv.reader()
Read as dictcsv.DictReader()
Write dictcsv.DictWriter()
Append data"a" mode
Change delimiterdelimiter=";"

Python Read/Write JSON

JSON in Python

JSON (JavaScript Object Notation) is used for storing and exchanging data, commonly in APIs and configuration files.

Python has a built-in module:

import json

Write (Save) JSON to a File

Example Dictionary/Data

data = {
    "name": "Deepesh",
    "age": 30,
    "skills": ["Python", "Selenium", "Automation"]
}

Save to JSON file

import json

with open("data.json", "w") as file:
    json.dump(data, file, indent=4)

indent=4 makes the JSON formatted & readable.


Read (Load) JSON from a File

import json

with open("data.json", "r") as file:
    content = json.load(file)
    print(content)

Output

{'name': 'Deepesh', 'age': 30, 'skills': ['Python', 'Selenium', 'Automation']}

Now content is a Python dictionary, and you can access elements like:

print(content["name"])
print(content["skills"][1])

Convert Python Data ↔ JSON String

Convert Python → JSON string

import json

person = {"city": "Delhi", "pin": 110001}
json_string = json.dumps(person)
print(json_string)

Convert JSON string → Python


Update JSON File

import json

# Read existing content
with open("data.json", "r") as file:
    data = json.load(file)

# Modify data
data["age"] = 31
data["skills"].append("API Testing")

# Write back to file
with open("data.json", "w") as file:
    json.dump(data, file, indent=4)

Work with Lists in JSON

Example JSON file (employees.json)

[
    {"id": 1, "name": "Ankit"},
    {"id": 2, "name": "Riya"}
]

Add a new record

import json

with open("employees.json", "r") as file:
    employees = json.load(file)

employees.append({"id": 3, "name": "Aman"})

with open("employees.json", "w") as file:
    json.dump(employees, file, indent=4)

Summary

TaskFunction
Write Python → JSON filejson.dump()
Read JSON file → Pythonjson.load()
Python → JSON stringjson.dumps()
JSON string → Pythonjson.loads()

Python Read/Write Excel File

openpyxl for Excel Handling

Install openpyxl (if not installed)

pip install openpyxl

from openpyxl import Workbook

wb = Workbook()                # Create workbook
ws = wb.active                 # Select active sheet
ws.title = "Students"          # Rename sheet

# Write data
ws['A1'] = "Name"
ws['B1'] = "Marks"
ws['A2'] = "Deepesh"
ws['B2'] = 85

wb.save("students.xlsx")       # Save file
print("File created successfully")

Using append()

from openpyxl import Workbook

wb = Workbook()
ws = wb.active

data = [
    ["Name", "Marks"],
    ["Ankit", 90],
    ["Riya", 88],
    ["Aman", 76]
]

for row in data:
    ws.append(row)

wb.save("marks.xlsx")
print("Data written successfully")

Read the whole sheet of data

from openpyxl import load_workbook

wb = load_workbook("marks.xlsx")
ws = wb.active

for row in ws.rows:
    for cell in row:
        print(cell.value, end="  |  ")
    print()

By cell address

from openpyxl import load_workbook

wb = load_workbook("marks.xlsx")
ws = wb.active

print(ws['A1'].value)   # Header
print(ws['B2'].value)   # Marks of 2nd row

By Row

for row in ws.iter_rows(min_row=1, max_row=4, values_only=True):
    print(row)

By Column

for col in ws.iter_cols(min_col=1, max_col=2, values_only=True):
    print(col)

from openpyxl import load_workbook

wb = load_workbook("marks.xlsx")
ws = wb.active

ws['B3'] = 95  # Update marks for row 3
wb.save("marks.xlsx")

print("File updated")


Delete Sheet

wb = load_workbook("marks.xlsx")
del wb["Summary"]
wb.save("marks.xlsx")


from openpyxl.styles import Font

ws['A1'].font = Font(bold=True, size=12, color="FF0000")
ws['B1'].font = Font(bold=True, size=12)
wb.save("marks.xlsx")

from openpyxl import Workbook

wb = Workbook()
ws = wb.active

data = [
    ["Name", "M1", "M2", "M3", "Total", "Average"],
    ["Raj", 85, 90, 88],
    ["Simran", 78, 82, 80],
]

for row in data:
    ws.append(row)

# Add formulas
ws['E2'] = "=B2+C2+D2"
ws['F2'] = "=E2/3"
ws['E3'] = "=B3+C3+D3"
ws['F3'] = "=E3/3"

wb.save("report.xlsx")
print("Report created!")

TaskMethod
Create fileWorkbook()
Load fileload_workbook()
Write cellws[‘A1’] = value
Append rowws.append()
Readws.rows, iter_rows()
FormattingFont()

Read Excel File

import openpyxl

def read_excel_file(file_path, sheet_name, cell_name):
# Load the workbook
workbook = openpyxl.load_workbook(file_path)
# Select the specified sheet
sheet = workbook[sheet_name]
# Read the value from the specified cell
cell_value = sheet[cell_name].value
print(f"Value in {cell_name} of sheet '{sheet_name}': {cell_value}")

# read one cell data
read_excel_file(file_path='users_data.xlsx', sheet_name='Sheet1', cell_name='A2')

Write Excel File

def write_excel_file(file_path, sheet_name, cell_name, data):
    # Load the workbook
    workbook = openpyxl.load_workbook(file_path)
    # Select the specified sheet
    sheet = workbook[sheet_name]
    # Write data to the specified cell
    sheet[cell_name] = data
    
    # Save the workbook
    workbook.save(file_path)
    print(f"Data written to sheet '{sheet_name}' starting at {cell_name}.")



write_excel_file(file_path='users_data.xlsx', sheet_name='Sheet1', cell_name='D2', data='Learning Excel with Python')

Variables Scope In Python

Variables declared inside a function are local to that function.


Variable declared outside a function can be accessed anywhere.


Use the global keyword to change it.


Inner function can access variable from the outer function.


The nonlocal keyword allows modifying a variable in the outer (enclosing) function.