Saturday, October 18, 2025

PP UNIT IV & WEEK IV PROGRAMS

 

UNIT-IV

Files: Types of Files, Creating and Reading Text Data, File Methods to Read and Write Data, Reading and Writing Binary Files, Pickle Module, Reading and Writing CSV Files, Python OSs and OS.path Modules.

Object-Oriented Programming: Classes and Objects, Creating Classes in Python, Creating Objects in Python, Constructor Method, Classes with Multiple Objects, Class Attributes Vs Data Attributes, Encapsulation, Inheritance, Polymorphism.

 

FILES

A file is a resource to store data. As part of the programming requirement, we may have to store our data permanently for future purpose. For this requirement we should go for files. Files are very common permanent storage areas to store our data.

OR

A file is used to store data permanently on the disk. In Python, we can read from and write to files easily using the built-in open() function.

 

Types of Files

  1. Text files (.txt, .csv, .py, etc.)
    • Store data in human-readable form (characters).
    • Example: "Hello World" stored in a .txt file.
  2. Binary files (.bin, .jpg, .mp3, .exe, etc.)
    • Store data in binary (0s and 1s).
    • Example: images, videos, executables.

 

 

 

Mode

Description

Example

"r"

Read mode (default). Opens file for reading. File must exist.

open("file.txt", "r")

"w"

Write mode. Creates a new file or overwrites an existing one.

open("file.txt", "w")

"a"

Append mode. Opens file and adds content at the end without deleting existing data.

open("file.txt", "a")

"x"

Exclusive creation. Creates a new file, but raises error if file already exists.

open("file.txt", "x")

"b"

Binary mode. Used for non-text files (images, videos, etc.).

open("image.jpg", "rb")

"t"

Text mode (default). Used for text files.

open("file.txt", "rt")

"r+"

Read & Write mode. File must exist.

open("file.txt", "r+")

"w+"

Write & Read mode. Creates/overwrites file.

open("file.txt", "w+")

"a+"

Append & Read mode. Creates file if not exists, appends otherwise.

open("file.txt", "a+")

 

Read mode "r"

f = open("sample.txt", "r")

print(f.read())

f.close()

2. Write mode "w"

f = open("sample.txt", "w")

f.write("This will overwrite the file content.")

f.close()

3. Append mode "a"

f = open("sample.txt", "a")

f.write("\nThis line is appended at the end.")

f.close()

4. Binary mode "rb" and "wb"

# Reading an image in binary mode

f = open("photo.jpg", "rb")

data = f.read()

f.close()

 

# Writing binary data

f = open("copy.jpg", "wb")

f.write(data)

f.close()

 

Shortcut:

  • r → read
  • w → write (overwrite)
  • a → append
  • x → create new
  • Add + → read + write
  • Add b → binary mode

 

Creating (Writing) Text Data:

To create a text file and store data in it, we use the open() function with write ("w") or append ("a") mode.

 

Example 1: Write data into a file

# Create (or overwrite) a file and write text into it

f = open("students.txt", "w")   # 'w' = write mode

f.write("Hello Students!\nWelcome to Python file handling.")

f.close()

print("File created and data written successfully.")

 What happens here?

  • If students.txt doesn’t exist, it is created.
  • If it exists, old data is erased and replaced.

 

Example 2: Append data into a file

f = open("students.txt", "a")   # 'a' = append mode

f.write("\nThis line is added later without deleting old data.")

f.close()

print("Data appended successfully.")

·         A mode keeps old content and adds new data at the end.

 

Reading Text Data

To read data from a file, we use the open() function with read ("r") mode.

Example 3: Read entire file

f = open("students.txt", "r")   # 'r' = read mode

content = f.read()

print("File Content:\n", content)

f.close()

·         read() → reads the entire file as a string.

 

Example 4: Read line by line

f = open("students.txt", "r")

for line in f:          # Iterating through file object

   print(line.strip()) # strip() removes extra newlines

f.close()

 

Example 5: Read only one line

f = open("students.txt", "r")

print(f.readline())   # Reads the first line

print(f.readline())   # Reads the next line

f.close()

 

Example 6: Read all lines into a list

f = open("students.txt", "r")

lines = f.readlines()   # Returns list of lines

print(lines)

f.close()

 

Best Practice (Using with)

with open("students.txt", "r") as f:

    data = f.read()

    print(data)

# File automatically closes after block ends

 

Summary:

  • Create/Write: "w" (overwrite), "a" (append).
  • Read: "r", "read(), readline(), readlines().
  • Use with → No need to call close().

Opening a Text File in Python

It is done using the open() function. No module is required to be imported for this function.

File_object = open(r"File_Name","Access_Mode")

Example: Here, file1 is created as an object for MyFile1 and file2 as object for MyFile2.

# Open function to open the file "MyFile1.txt"

# (same directory) in append mode and

file1 = open("MyFile1.txt","a")

 

# store its reference in the variable file1

# and "MyFile2.txt" in D:\Text in file2

file2 = open(r"D:\Text\MyFile2.txt","w+")

 

Python Read Text File:

There are three ways to read txt file in Python:

  • Using read()
  • Using readline()

 

Reading From a File Using read():

read(): Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.

File_object.read([n])

Reading a Text File Using readline():

readline(): Reads a line of the file and returns in form of a string.For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line.

File_object.readline([n])

 

 

Reading a File Using readlines():

readlines(): Reads all the lines and return them as each line a string element in a list.

  File_object.readlines()

Note: '\n' is treated as a special character of two bytes.

In this example, a file named "myfile.txt" is created and opened in write mode ( "w" ). Data is written to the file using write and write lines methods. The file is then reopened in read and append mode ( "r+" ). Various read operations, including read, read line , read lines , and the use of seek , demonstrate different ways to retrieve data from the file. Finally, the file is closed.

 

CODE:

file1 = open("myfile.txt", "w")

L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]

 

# \n is placed to indicate EOL (End of Line)

file1.write("Hello \n")

file1.writelines(L)

file1.close()  # to change file access modes

 

file1 = open("myfile.txt", "r+")

 

print("Output of Read function is ")

print(file1.read())

print()

 

# seek(n) takes the file handle to the nth

# byte from the beginning.

file1.seek(0)

 

print("Output of Readline function is ")

print(file1.readline())

print()

 

file1.seek(0)

 

# To show difference between read and readline

print("Output of Read(9) function is ")

print(file1.read(9))

print()

 

file1.seek(0)

 

print("Output of Readline(9) function is ")

print(file1.readline(9))

 

file1.seek(0)

# readlines function

print("Output of Readlines function is ")

print(file1.readlines())

print()

file1.close()

 

OUTPUT:

Output of Read function is

Hello

This is Delhi

This is Paris

This is London

 

Output of Readline function is

Hello

 

Output of Read(9) function is

Hello

Th

 

Output of Readline(9) function is

Hello

 

Output of Readlines function is

['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']

 

 

Write to Text File in Python

There are two ways to write in a file:

  • Using write()
  • Using writelines()

 

Writing to a Python Text File Using write()

write(): Inserts the string str1 in a single line in the text file.

 

File_object.write(str1)

file = open("Employees.txt", "w")

 

for i in range(3):

name = input("Enter the name of the employee: ")

file.write(name)

file.write("\n")

           

file.close()

 

print("Data is written into the file.")

Output:

Data is written into the file.

 

Writing to a Text File Using writelines()

writelines(): For a list of string elements, each string is inserted in the text file. Used to insert multiple strings at a single time.

 

File_object.writelines(L) for L = [str1, str2, str3]

file1 = open("Employees.txt", "w")

lst = [ ]

for i in range(3):

            name = input("Enter the name of the employee: ")

            lst.append(name + '\n')

           

file1.writelines(lst)

file1.close()

print("Data is written into the file.")

Output:

Data is written into the file.

 

Reading and Writing Binary Files

What is a Binary File?

  • A binary file stores data in the same way as it is held in memory — as bytes (0s and 1s), not as plain text.
  • Examples: images (.jpg, .png), audio, videos, and even compiled programs.

In Python, you use 'rb' (read binary) and 'wb' (write binary) modes to handle them.

 

 

Opening Modes for Binary Files:

 

Mode

Description

'wb'

Write to a binary file (overwrites if exists)

'rb'

Read from a binary file

'ab'

Append to a binary file

'wb+'

Write and read both

'rb+'

Read and write both

 

 

Example: Writing and Reading a Binary File

 

Step 1: Write binary data

# Writing data to a binary file

 

data = b"Python is fun with binary files!"  # 'b' prefix means bytes

 

with open("example.bin", "wb") as f:

    f.write(data)

 

print("Data written to binary file successfully!")

 

Step 2: Read binary data

# Reading data from the binary file

 

with open("example.bin", "rb") as f:

    content = f.read()

 

print("Data read from binary file:")

print(content)

 

Output:

Data written to binary file successfully!

Data read from binary file:

b'Python is fun with binary files!'

 

Example 2: Copying an image (binary file)

You can use binary mode to copy non-text files like images:

# Copy an image using binary read/write

 

with open("input_image.jpg", "rb") as f1:

    data = f1.read()

 

with open("copy_image.jpg", "wb") as f2:

    f2.write(data)

 

print("Image copied successfully in binary mode!")

 

Key Points

  • Use binary mode for non-text data (images, videos, etc.).
  • Binary data cannot be edited like text — it’s raw bytes.
  • Always use with open(...) to handle files safely (auto-closes file).

 

 

Pickle Module:

 

·         Pickle is a built-in Python module used to serialize and deserialize Python objects.

·         Serialization (Pickling): Converting a Python object (like list, dict, set, etc.) into a byte stream (so it can be saved in a file or sent over a network).

·         Deserialization (Unpickling): Converting the byte stream back into the original Python object.

 

 

Why Use Pickle?

Because normal text or binary write operations can’t directly store complex objects (like lists, dictionaries, or custom classes).
Pickle lets you easily save and load them.

 

Using Pickle in Python

 

Step 1: Import pickle and create data

 

CODE:

import pickle

 

# Create a Python object (dictionary)

student_data = {

    "name": "Alice",

    "age": 22,

    "subjects": ["Python", "Data Science", "AI"]

}

 

Step 2: Pickling (Write object to a binary file)

# Open a binary file to write the data

with open("student.pkl", "wb") as file:

    pickle.dump(student_data, file)

 

print("Data successfully pickled (saved)!")

 

Step 3: Unpickling (Read object back from file)

# Open the binary file to read the data

with open("student.pkl", "rb") as file:

    loaded_data = pickle.load(file)

 

print("Data successfully unpickled (loaded)!")

print("Loaded Data:", loaded_data)

 

OUTPUT:

 

Data successfully pickled (saved)!

Data successfully unpickled (loaded)!

Loaded Data: {'name': 'Alice', 'age': 22, 'subjects': ['Python', 'Data Science', 'AI']}

 

Key Functions in pickle Module:

 

Function

Description

pickle.dump(obj, file)

Write (pickle) object to a binary file

pickle.load(file)

Read (unpickle) object from a binary file

pickle.dumps(obj)

Convert object to bytes (without writing to file)

pickle.loads(bytes)

Convert bytes back to object

 

 

·         Always open files in binary mode ('wb' or 'rb').

·         Pickled files are not human-readable.

·         Never unpickle data from an untrusted source — it may execute malicious code.

 

 

Reading and Writing CSV Files

CSV File?

  • CSV (Comma-Separated Values) is a plain text file where data is stored in rows, and each value is separated by a comma.

Example of a CSV file:

name,age,city

Alice,22,Delhi

Bob,25,Mumbai

      Charlie,23,Chennai

 

Python’s csv Module

Python provides a built-in csv module to handle reading and writing CSV files easily.

Example 1: Writing to a CSV File

import csv

# Data to write

data = [

    ["name", "age", "city"],

    ["Alice", 22, "Delhi"],

    ["Bob", 25, "Mumbai"],

    ["Charlie", 23, "Chennai"]

]

# Writing data to CSV file

with open("students.csv", "w", newline="") as file:

    writer = csv.writer(file)

    writer.writerows(data)

 

print("Data written successfully to students.csv")

 

OUTPUT:

name,age,city

Alice,22,Delhi

Bob,25,Mumbai

Charlie,23,Chennai

 

 

Example 2: Reading from a CSV File

import csv

 

# Reading data from CSV file

with open("students.csv", "r") as file:

    reader = csv.reader(file)

    for row in reader:

        print(row)

 

OUTPUT:

['name', 'age', 'city']

['Alice', '22', 'Delhi']

['Bob', '25', 'Mumbai']

['Charlie', '23', 'Chennai']

 

Example 3: Using DictWriter and DictReader

This is more convenient when working with column names.

 

Writing using DictWriter

 

import csv

 

# Data as list of dictionaries

data = [

    {"name": "Alice", "age": 22, "city": "Delhi"},

    {"name": "Bob", "age": 25, "city": "Mumbai"},

    {"name": "Charlie", "age": 23, "city": "Chennai"}

]

 

# Write to CSV file

with open("students_dict.csv", "w", newline="") as file:

    fieldnames = ["name", "age", "city"]

    writer = csv.DictWriter(file, fieldnames=fieldnames)

   

    writer.writeheader()  # write column names

    writer.writerows(data)

 

print("Data written successfully using DictWriter!")

 

Reading using DictReader

import csv

 

# Read from CSV file

with open("students_dict.csv", "r") as file:

    reader = csv.DictReader(file)

    for row in reader:

        print(row)

 

OUTPUT:

{'name': 'Alice', 'age': '22', 'city': 'Delhi'}

{'name': 'Bob', 'age': '25', 'city': 'Mumbai'}

{'name': 'Charlie', 'age': '23', 'city': 'Chennai'}

 

Key Points:

Function

Description

csv.writer(file)

Create writer object for writing rows

writer.writerow()

Write a single row

writer.writerows()

Write multiple rows

csv.reader(file)

Create reader object for reading rows

csv.DictWriter()

Write using dictionaries

csv.DictReader()

Read as dictionaries

newline=""

Avoids extra blank lines in Windows

 

 

Python os and os.path Modules.

 

What is the os Module?

The os module provides a way to use operating system-dependent functionality — like creating, removing, navigating, or renaming files and directories.

 

What is the os.path Module?

The os.path submodule helps you work with file paths — such as joining, splitting, or checking whether a path exists.

 

CODE:

import os

 

# ---- OS MODULE EXAMPLES ----

 

# 1. Get current working directory

print("Current Working Directory:", os.getcwd())

 

# 2. Create a new directory

os.mkdir("test_folder")

print("Created directory: test_folder")

 

# 3. List files and folders in current directory

print("Contents of current directory:", os.listdir())

 

# 4. Rename the directory

os.rename("test_folder", "new_folder")

print("Renamed 'test_folder' to 'new_folder'")

 

# 5. Remove the directory

os.rmdir("new_folder")

print("Removed directory: new_folder")

 

# ---- OS.PATH MODULE EXAMPLES ----

file_path = "example.txt"

 

# 6. Create a file for testing

with open(file_path, "w") as f:

    f.write("Hello, OS module in Python!")

 

# 7. Check if file exists

print("File exists:", os.path.exists(file_path))

 

# 8. Get absolute path

print("Absolute path:", os.path.abspath(file_path))

 

# 9. Get directory name

print("Directory name:", os.path.dirname(os.path.abspath(file_path)))

 

# 10. Get base file name

print("Base file name:", os.path.basename(file_path))

 

# 11. Get file size

print("File size (bytes):", os.path.getsize(file_path))

 

OUTPUT:

Current Working Directory: /content

Created directory: test_folder

Contents of current directory: ['.config', 'example.bin', 'students_dict.csv', 'source.txt', 'students.csv', 'source.text.txt', 'student.pkl', 'test_folder', 'sample_data']

Renamed 'test_folder' to 'new_folder'

Removed directory: new_folder

File exists: True

Absolute path: /content/example.txt

Directory name: /content

Base file name: example.txt

File size (bytes): 27

 

Common os and os.path Functions

Module

Function

Description

os

os.getcwd()

Get current working directory

os

os.chdir(path)

Change directory

os

os.mkdir(path)

Create a directory

os

os.rmdir(path)

Remove a directory

os

os.listdir(path)

List files and folders

os

os.remove(file)

Delete a file

os

os.rename(src, dest)

Rename a file or directory

os.path

os.path.exists(path)

Check if a file/directory exists

os.path

os.path.join(a, b)

Join two path components

os.path

os.path.abspath(path)

Get absolute path

os.path

os.path.basename(path)

Get filename from path

os.path

os.path.dirname(path)

Get directory path

os.path

os.path.getsize(path)

Get file size in bytes

 

 

Object-Oriented Programming (OOP)?

 

Object-Oriented Programming is a programming paradigm (style) based on the concept of objects, which can contain data (attributes) and code (methods).

It helps to model real-world entities and makes code:

  • More organized
  • Reusable
  • Easy to maintain and extend

 

 

Key OOP Concepts in Python

 

Concept

Description

Class

A blueprint or template for creating objects (defines properties and behavior).

Object

An instance of a class (a real example created from the class).

Attributes

Variables that belong to an object (data).

Methods

Functions defined inside a class that operate on the object’s data.

Constructor (__init__)

Special method that runs automatically when an object is created.

Self

Refers to the current object (used to access variables and methods of the class).

 

 

Class

 Definition:

A class is a blueprint or template for creating objects.
It defines data (attributes) and functions (methods) that describe what an object can have and do.

In short:

“A class is a user-defined data type that represents a real-world entity.”

 

Example of a Class:

class Student:

    # attributes (data)

    name = "John"

    age = 20

 

    # method (function)

    def display(self):

        print("Name:", self.name)

        print("Age:", self.age)

 

 

·         Student is a class.

·         It has attributes (name, age) and a method (display()).

 

class Student:

    def __init__(self, name, age):

        self.name = name      # instance variable

        self.age = age        # instance variable

 

    def display(self):

        print("Name:", self.name)

        print("Age:", self.age)

 

Explanation

  • class Student: → defines a new class.
  • __init__ → constructor, called when an object is created.
  • self → refers to the current object.
  • self.name and self.age → object attributes.
  • display() → method to show student details.

 

 

Object?

Definition:

An object is an instance (real example) of a class.
It is created using the class blueprint and can access class data and methods.

In short:

“An object is a specific example created from a class.”

 

Example of an Object:

# Create object of class

s1 = Student()

 

# Access class attributes and method

s1.display()

 

 

OUTPUT:

Name: John

Age: 20

 

Here,

  • s1 is an object of the Student class.
  • It uses the display() method to show data.

 

Creating an Object (Instance)

# Creating objects of the class

s1 = Student("Alice", 21)

s2 = Student("Bob", 22)

 

# Calling methods

s1.display()

s2.display()

 

Output

Name: Alice

Age: 21

Name: Bob

Age: 22                                        

 

 

Class vs Object — Easy Comparison:

 

Feature

Class

Object

Meaning

Blueprint or template

Instance of the class

Creation

Defined using class keyword

Created using class name (e.g. obj = ClassName())

Contains

Attributes and Methods

Actual data stored in memory

Example

class Car:

my_car = Car()

 

Another Example — Car Class

class Car:

    def __init__(self, brand, color):

        self.brand = brand

        self.color = color

 

    def show_details(self):

        print("Car Brand:", self.brand)

        print("Car Color:", self.color)

 

# Create objects

car1 = Car("Toyota", "Red")

car2 = Car("BMW", "Black")

 

car1.show_details()

car2.show_details()

 

 

Output:

Car Brand: Toyota

Car Color: Red

Car Brand: BMW

Car Color: Black

 

Explanation:

  • Car → class
  • car1, car2 → objects
  • Each object has its own brand and color values
  • __init__() is a constructor that initializes object data

 

Concept

Explanation

Class

Blueprint or design for creating objects

Object

Real-world entity created from a class

Attributes

Variables that hold data inside a class

Methods

Functions defined inside a class to operate on data

Constructor (__init__)

Special method that initializes object data automatically when object is created

 

4 main pillars of Object-Oriented Programming (OOP) in Python:

Encapsulation
Inheritance
Polymorphism
Abstraction

We’ll define each one in simple words, then see a small, easy-to-understand example for each.

 

ü  Encapsulation

Definition:

Encapsulation means binding data (variables) and methods (functions) that work on that data into a single unit — a class.
It also helps to hide internal details of an object from the outside world.

In short:

“Keep your data safe and access it only through methods.”

 

Example:

class Student:

    def __init__(self, name, marks):

        self.__name = name       # private variable (using __)

        self.__marks = marks

 

    def display(self):

        print("Name:", self.__name)

        print("Marks:", self.__marks)

 

# Create object

s = Student("Alice", 90)

s.display()

 

# Accessing private variable directly gives error

# print(s.__name) 

 

# Access using method

 

Output:

Name: Alice

Marks: 90

Here, __name and __marks are hidden (private).
They can only be accessed using the display() method — that’s encapsulation.

 

ü  Inheritance

Definition:

Inheritance means one class (child) can use the properties and methods of another class (parent).
It promotes code reusability.

In short:

“Child class inherits features of parent class.”

 Example:

# Parent class

class Animal:

    def speak(self):

        print("Animals can speak")

 

# Child class

class Dog(Animal):

    def bark(self):

        print("Dog barks")

 

# Create object

d = Dog()

d.speak()   # Inherited method

d.bark()    # Child's own method

 

Output:

Animals can speak

Dog barks

 

Here, Dog inherited the speak() method from Animal.

 

ü  Polymorphism

Definition:

Polymorphism means many forms — same method name but different behavior depending on the object.

In short:

“Same function name works differently for different classes.”

 

Example:

class Bird:

    def sound(self):

        print("Chirping")

 

class Dog:

    def sound(self):

        print("Barking")

 

# Function showing polymorphism

def animal_sound(animal):

    animal.sound()

 

# Using same function for different objects

b = Bird()

d = Dog()

 

animal_sound(b)

animal_sound(d)

 

Output:

Chirping

Barking

Both Bird and Dog have a sound() method,
but their behaviors are different — that’s polymorphism.

 

ü  Abstraction

Definition:

Abstraction means showing only essential features and hiding the complex details from the user.
We do this using abstract classes and abstract methods.

In short:

“Hide unnecessary details — show only what’s important.”

 

Example:

from abc import ABC, abstractmethod

 

# Abstract class

class Shape(ABC):

    @abstractmethod

    def area(self):

        pass

 

# Subclass 1

class Circle(Shape):

    def __init__(self, radius):

        self.radius = radius

    def area(self):

        return 3.14 * self.radius ** 2

 

# Subclass 2

class Square(Shape):

    def __init__(self, side):

        self.side = side

    def area(self):

        return self.side ** 2

 

# Using subclasses

c = Circle(5)

s = Square(4)

 

print("Circle Area:", c.area())

print("Square Area:", s.area())

 

Output:

Circle Area: 78.5

Square Area: 16

Here, Shape defines an abstract method area() (no details).
Circle and Square implement it differently — that’s abstraction.

 

Creating Classes in Python

Definition:

A class is created using the keyword class.
It acts as a blueprint that defines attributes (data) and methods (functions) that its objects will have.

Example:

class Student:

    # Class attributes

    college = "ABC College"

 

    # Method

    def show(self):

        print("This is a Student class.")

Here:

  • Student is the class name
  • college is a class attribute
  • show() is a method

 

Creating Objects in Python

Definition:

An object is an instance of a class.
You create it by calling the class name like a function.

Example:

# Create object

s1 = Student()

 

# Access class method using object

s1.show()

 

# Access class attribute

print("College Name:", s1.college)

 

Output:

This is a Student class.

College Name: ABC College

Note: Each object created from a class can access the same attributes and methods.

 

Constructor Method (__init__())

Definition:

The constructor is a special method named __init__().
It is automatically called whenever an object is created.
It is used to initialize object attributes.

 

Syntax:

class ClassName:

    def __init__(self, parameters):

        # Initialize attributes

 

Example:

class Student:

    # Constructor

    def __init__(self, name, age):

        self.name = name   # instance attribute

        self.age = age

 

    # Method

    def show(self):

        print("Name:", self.name)

        print("Age:", self.age)

 

# Create objects

s1 = Student("Alice", 20)

s2 = Student("Bob", 22)

 

# Call method

s1.show()

s2.show()

 

Output:

Name: Alice

Age: 20

Name: Bob

Age: 22

 

Explanation:

  • __init__() runs automatically when you create an object.
  • self refers to the current object.
  • Each object stores its own data (name and age).

 

Classes with Multiple Objects

You can create many objects from a single class, each with different attribute values.

Example:

class Car:

    def __init__(self, brand, color):

        self.brand = brand

        self.color = color

 

    def show(self):

        print("Brand:", self.brand, "| Color:", self.color)

 

# Create multiple objects

car1 = Car("Toyota", "Red")

car2 = Car("BMW", "Black")

car3 = Car("Tesla", "White")

 

# Display details

car1.show()

car2.show()

car3.show()

 

 

Output:

Brand: Toyota | Color: Red

Brand: BMW | Color: Black

Brand: Tesla | Color: White

 

Explanation:

  • Each object (car1, car2, car3) is independent.
  • All share the same class definition but hold different data.

 

Concept

Description

Example

Class

Blueprint for objects

class Student:

Object

Instance of a class

s1 = Student()

Constructor (__init__)

Initializes object attributes

def __init__(self, name):

Multiple Objects

Many instances of same class

s1, s2, s3 = Student(...)

 

 

Class Attributes Vs Data Attributes

 

Class Attributes?

 Definition:

A class attribute is a variable that is shared by all objects of a class.
It is defined inside the class, but outside any methods.

All objects (instances) share the same value of a class attribute, unless you change it for one specific object.

 

Example:

class Student:

    college = "ABC College"   # Class Attribute

 

    def __init__(self, name, age):

        self.name = name      # Instance (Data) Attribute

        self.age = age

 

# Create two objects

s1 = Student("Alice", 20)

s2 = Student("Bob", 22)

 

# Access class attribute

print("College (s1):", s1.college)

print("College (s2):", s2.college)

 

Output:

College (s1): ABC College

College (s2): ABC College

 

 Both s1 and s2 share the same class attribute college.

 

Data (Instance) Attributes?

 

Definition:

A data (instance) attribute belongs to a specific object.
It is defined using self inside the __init__() method.

Each object can have different values for these attributes.

 

Example:

print("Name:", s1.name, "| Age:", s1.age)

print("Name:", s2.name, "| Age:", s2.age)

 

 Output:

Name: Alice | Age: 20

Name: Bob | Age: 22

 

 Each object has its own copy of name and age.

 

 

Class Attribute vs Instance Attribute (Comparison)

 

Feature

Class Attribute

Instance (Data) Attribute

Defined

Inside class, outside any method

Inside constructor (__init__) using self

Belongs to

The class (shared by all objects)

Each object individually

Memory

Single copy shared among all objects

Separate copy for each object

Accessed by

Class name or object name

Only through object

Example

college = "ABC College"

self.name = name

Change effect

Affects all objects

Affects only that object

 

Combined Example

class Student:

    # Class attribute

    college = "ABC College"

 

    def __init__(self, name, age):

        # Instance attributes

        self.name = name

        self.age = age

 

# Create objects

s1 = Student("Alice", 20)

s2 = Student("Bob", 22)

 

print("Before change:")

print(s1.name, "-", s1.college)

print(s2.name, "-", s2.college)

 

# Change class attribute using class name

Student.college = "XYZ University"

 

print("\nAfter class attribute change:")

print(s1.name, "-", s1.college)

print(s2.name, "-", s2.college)

 

# Change instance attribute for one object

s1.name = "Alicia"

 

print("\nAfter instance attribute change:")

print(s1.name, "-", s1.college)

print(s2.name, "-", s2.college)

 

Output:

Before change:

Alice - ABC College

Bob - ABC College

 

After class attribute change:

Alice - XYZ University

Bob - XYZ University

 

After instance attribute change:

Alicia - XYZ University

Bob - XYZ University

 

Term

Description

Example

Class Attribute

Shared among all objects

Student.college

Instance Attribute

Unique to each object

self.name, self.age

When Used

When the data is common for all objects

When data varies per object

 

 

**********************************



 

WEEK 4 Programs:

 

1. Command Line / Terminal (Most Common)

Save your program in a file, e.g., program.py.

 

  • Open a terminal/command prompt.
  • Navigate to the folder where the file is saved:

·         cd path/to/your/file

Run the file:

·         python program.py

(Use python3 instead of python on Linux/Mac if needed.)

2. IDLE (Python’s Built-in IDE)

·         Open IDLE (comes with Python).

·         Go to File → Open… and select your .py file.

·         Press F5 (or Run → Run Module).

·         Output will appear in the IDLE shell.

3. VS Code (Visual Studio Code)

·         Install VS Code.

·         Install Python Extension (by Microsoft).

·         Open your .py file in VS Code.

·         Run:

o    Press Run  in the top right corner.

o    Or use terminal inside VS Code:

bash

python program.py

 

4. PyCharm

·         Install PyCharm.

·         Open a new project or import your existing one.

·         Right-click your Python file → Run 'program'.

·         Output shows in PyCharm’s console.

 

5. Jupyter Notebook

·         Install Jupyter:

bash
pip install notebook

·         Start it:

bash
jupyter notebook

·         A browser window opens → you can open .ipynb or create a new notebook.

·         To run .py files:

python

%run program.py

 

6. Google Colab (Online)

·         Open Google Colab.

·         Upload your .py file or copy-paste the code.

·         Run a cell with:

python
!python program.py

·         Great for cloud execution (no installation needed).

7. Anaconda / Spyder

·         Install Anaconda (includes Spyder IDE).

·         Open Spyder → open your .py file.

·         Click Run 

·         Output appears in Spyder’s console.

ü  For beginners → IDLE or VS Code.

ü  For data science → Jupyter Notebook / Colab.

ü  For advanced development → PyCharm / VS Code.

ü  For quick testing → Command Line.

 

  NOTE:

·         For 1st  to 3rd  Program write a separate program in notepad and save it with source.txt and sorted_words.txt

·         Save that file in drive with separate folder and upload it in Google colab        

·         Now write a program in Google colab and run you will get your output

 

Program

1. Write a program to sort words in a file and put them in another file. The output file should have only lower-case words, so any upper-case words from source must be lowered.

 CODE:

 

# Create a source.txt file with some words

with open("source.txt", "w") as f:

    f.write("Apple orange Banana grape Cherry Mango Kiwi")

 

# Program to read words from a file, sort them, and write to another file in lowercase

 

# Input and output file names

input_file = "source.txt"

output_file = "sorted_words.txt"

 

# Step 1: Read all words from the input file

with open(input_file, "r") as f:

    text = f.read()

 

# Step 2: Convert text to lowercase and split into words

words = text.lower().split()

 

# Step 3: Sort words alphabetically

words.sort()

 

# Step 4: Write sorted words into the output file

with open(output_file, "w") as f:

    for word in words:

        f.write(word + "\n")

 

print("Words have been sorted and saved in", output_file)

 

OUTPUT:

Words have been sorted and saved in sorted_words.txt

 

# Display the sorted words file

with open("sorted_words.txt", "r") as f:

    print(f.read())

 

OUTPUT:

apple

banana

cherry

grape

kiwi

mango

orange

 

2. Python program to print each line of a file in reverse order.

 CODE:

# Program to print each line of a file in reverse order

 

# Input file name

input_file = "source.text.txt" # Corrected filename

 

# Open and read file

with open(input_file, "r") as f:

    lines = f.readlines()

 

# Print each line in reverse

print("Reversed lines:\n")

for line in lines:

    # Strip newline, reverse, then print

    print(line.strip()[::-1])

 

 

(Optional) — Save reversed lines into another file

output_file = "reversed.txt"

 

with open(output_file, "w") as f:

    for line in lines:

        f.write(line.strip()[::-1] + "\n")

 

print(f"Reversed lines saved in {output_file}")

 

 

OUTPUT:

Reversed lines:

 

elppA

ananab

yreehc

iwik

eparg

 

 

3. Python program to compute the number of characters, words and lines in a file.

 

CODE:

 # Input file name

filename = "source.txt"

 

# Initialize counters

num_lines = 0

num_words = 0

num_chars = 0

 

# Open and read file

with open(filename, "r") as f:

    for line in f:

        num_lines += 1

        num_words += len(line.split())

        num_chars += len(line)

 

# Display the results

print("Number of lines:", num_lines)

print("Number of words:", num_words)

print("Number of characters:", num_chars)

 

 

OUTPUT:

Number of lines: 5

Number of words: 5

Number of characters: 34

 

Explanation:

·         len(line.split()) → counts words in a line.

·         len(line) → counts all characters including spaces and newline (\n).

·         num_lines += 1 → counts total lines.

 

 

4. Write a program to create, display, append, insert and reverse the order of the items in the array.

 CODE:

from array import array

 

# Step 1: Create an array of integers

arr = array('i', [10, 20, 30, 40, 50])

print("Original array:", arr.tolist())

 

# Step 2: Display array elements

print("Array elements:")

for i in arr:

    print(i, end=" ")

print()

 

# Step 3: Append an element

arr.append(60)

print("\nAfter appending 60:", arr.tolist())

 

# Step 4: Insert an element at a specific position

arr.insert(2, 25)  # insert 25 at index 2

print("After inserting 25 at index 2:", arr.tolist())

 

# Step 5: Reverse the array

arr.reverse()

print("After reversing:", arr.tolist())

 

OUTPUT:

Original array: [10, 20, 30, 40, 50]

Array elements:

10 20 30 40 50

 

After appending 60: [10, 20, 30, 40, 50, 60]

After inserting 25 at index 2: [10, 20, 25, 30, 40, 50, 60]

After reversing: [60, 50, 40, 30, 25, 20, 10]

 

Explanation

·         array('i', [...]) → creates an integer array.

·         append() → adds an item at the end.

·         insert(index, value) → inserts at a specific index.

·         reverse() → reverses the array in place.

·         tolist() → converts the array to a normal Python list for easy printing.

 

 

5. Write a program to add, transpose and multiply two matrices.

 CODE:

# Program to add, transpose, and multiply two matrices

 

# Step 1: Define two matrices

A = [

    [1, 2, 3],

    [4, 5, 6],

    [7, 8, 9]

]

 

B = [

    [9, 8, 7],

    [6, 5, 4],

    [3, 2, 1]

]

 

# Step 2: Matrix Addition

add_result = [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in range(len(A))]

 

# Step 3: Transpose of Matrix A

transpose_A = [[A[j][i] for j in range(len(A))] for i in range(len(A[0]))]

 

# Step 4: Matrix Multiplication (A × B)

multiply_result = [[sum(A[i][k] * B[k][j] for k in range(len(B))) for j in range(len(B[0]))] for i in range(len(A))]

 

# Step 5: Display Results

print("Matrix A:")

for row in A:

    print(row)

 

print("\nMatrix B:")

for row in B:

    print(row)

 

print("\nAddition of A and B:")

for row in add_result:

    print(row)

 

print("\nTranspose of A:")

for row in transpose_A:

    print(row)

 

print("\nMultiplication of A and B:")

for row in multiply_result:

    print(row)

 

OUTPUT:

 

Matrix A:

[1, 2, 3]

[4, 5, 6]

[7, 8, 9]

 

Matrix B:

[9, 8, 7]

[6, 5, 4]

[3, 2, 1]

 

Addition of A and B:

[10, 10, 10]

[10, 10, 10]

[10, 10, 10]

 

Transpose of A:

[1, 4, 7]

[2, 5, 8]

[3, 6, 9]

 

Multiplication of A and B:

[30, 24, 18]

[84, 69, 54]

[138, 114, 90]

 

Explanation

·         Addition: Add elements at the same positions.

·         Transpose: Swap rows with columns.

·         Multiplication: Use dot product of rows and columns.

 


 6. Write a Python program to create a class that represents a shape. Include methods to calculate its area and perimeter. Implement subclasses for different shapes like circle, triangle, and square.

 CODE:

Program: Shape Class with Subclasses

 

import math

 

# Base class

class Shape:

    def area(self):

        return 0

   

    def perimeter(self):

        return 0

 

 

# Subclass: Circle

class Circle(Shape):

    def __init__(self, radius):

        self.radius = radius

 

    def area(self):

        return math.pi * self.radius ** 2

 

    def perimeter(self):

        return 2 * math.pi * self.radius

 

 

# Subclass: Square

class Square(Shape):

    def __init__(self, side):

        self.side = side

 

    def area(self):

        return self.side ** 2

 

    def perimeter(self):

        return 4 * self.side

 

 

# Subclass: Triangle

class Triangle(Shape):

    def __init__(self, a, b, c):

        self.a = a

        self.b = b

        self.c = c

 

    def perimeter(self):

        return self.a + self.b + self.c

 

    def area(self):

        # Using Heron's Formula

        s = self.perimeter() / 2

        return math.sqrt(s * (s - self.a) * (s - self.b) * (s - self.c))

 

 

# ---- Test the classes ----

 

# Create objects

circle = Circle(5)

square = Square(4)

triangle = Triangle(3, 4, 5)

 

# Display results

print("Circle: Area =", round(circle.area(), 2), "Perimeter =", round(circle.perimeter(), 2))

print("Square: Area =", square.area(), "Perimeter =", square.perimeter())

print("Triangle: Area =", round(triangle.area(), 2), "Perimeter =", triangle.perimeter())

 

 

OUTPUT:

Circle: Area = 78.54 Perimeter = 31.42

Square: Area = 16 Perimeter = 16

Triangle: Area = 6.0 Perimeter = 12

 

Concepts Used

  • Base class (Shape) defines common methods (area() and perimeter()).
  • Subclasses (Circle, Square, Triangle) override these methods.
  • Heron’s formula is used to calculate the triangle’s area.




 

 

 

 

 

 

 

 

 

No comments:

Post a Comment

PP UNIT IV & WEEK IV PROGRAMS

  UNIT-IV Files: Types of Files, Creating and Reading Text Data, File Methods to Read and Write Data, Reading and Writing Binary Files, Pi...