[Go to site: main page, start]

0% found this document useful (0 votes)
2 views28 pages

Python Programming Notes R25

it is jntuh python programing notes for B.Tech MECH,AERO,EEE
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views28 pages

Python Programming Notes R25

it is jntuh python programing notes for B.Tech MECH,AERO,EEE
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

TABLE OF CONTENTS

UNIT 1 – Introduction to Python and Basics of Programming


› Features & Applications
› Installation & IDEs
› Syntax, Indentation & Comments
› Variables & Data Types
› Type Casting
› Operators
› Input/Output Functions
› Control Structures
› Loops

UNIT 2 – Data Structures in Python


› Strings – Creation, Indexing, Slicing, Methods
› Lists – Creation, Methods, Comprehension
› Tuples – Properties, Indexing, Methods
› Sets – Operations, Methods
› Dictionaries – Creation, Access, Comprehension

UNIT 3 – Functions and Modules


› Defining & Calling Functions
› Parameters & Return Values
› Types of Arguments
› Scope of Variables
› Lambda Functions
› Map, Filter, Reduce, Recursion
› Modules – Creating & Importing
› Standard Modules (math, random, datetime)

UNIT 4 – File Handling and Exception Handling


› File Handling – Open, Read, Write, Append
› File Modes & Methods
› Working with CSV & JSON
› Exception Handling – try/except/finally
› Built-in & Custom Exceptions
› Regular Expressions (re module)

UNIT 5 – Object-Oriented Programming and Applications


› Classes, Objects, Attributes, Methods
› Constructor (__init__) & self
› Inheritance – Types
› Encapsulation & Polymorphism
› Method Overriding & Overloading
› Applications – Data Processing Script, Calculator, File Organizer, pandas
UNIT 1
Introduction to Python and Basics of Programming
Features • Applications • Syntax • Variables • Data Types • Operators • Control Structures • Loops

1.1 Introduction to Python


Python is a high-level, interpreted, general-purpose programming language created by Guido van
Rossum and first released in 1991. It emphasizes code readability and simplicity, allowing developers to
express concepts in fewer lines of code than languages like C++ or Java.

Key Features of Python


• Simple and Readable: Python syntax is close to English, making it easy to learn and understand.
• Interpreted: Code is executed line-by-line; no compilation needed.
• Dynamically Typed: No need to declare variable types; Python infers them at runtime.
• Object-Oriented: Supports classes, objects, inheritance, polymorphism, and encapsulation.
• Extensive Libraries: Rich standard library + third-party libraries (NumPy, pandas, Django, Flask,
etc.).
• Platform Independent: Write once, run anywhere – Windows, Mac, Linux.
• Free and Open Source: Python is freely downloadable and its source code is open.
• High-Level Language: Abstracts complex memory management from programmers.

Applications of Python
• Web Development (Django, Flask, FastAPI)
• Data Science & Machine Learning (NumPy, pandas, scikit-learn, TensorFlow)
• Automation & Scripting
• Scientific Computing
• Game Development (Pygame)
• Desktop GUI Applications (Tkinter)
• Network Programming
• Database Programming
• Artificial Intelligence

1.2 Installation & IDEs


To install Python, download the latest version from [Link]. During installation on Windows, check
'Add Python to PATH'. Verify installation by typing python --version in the terminal.

Popular IDEs for Python


• IDLE: Comes bundled with Python. Good for beginners.
• PyCharm: Feature-rich IDE by JetBrains. Best for large projects.
• VS Code: Lightweight, fast, with Python extension. Widely used.
• Jupyter Notebook: Browser-based, cell-by-cell execution. Best for Data Science.
• Spyder: Scientific Python IDE, similar to MATLAB.
• Google Colab: Free cloud-based Jupyter Notebook by Google.

1.3 Python Syntax, Indentation & Comments


Python uses indentation (whitespace) to define blocks of code, unlike C/Java which use curly braces {}.
Consistent indentation is mandatory; mixing tabs and spaces causes an IndentationError.
# This is a single-line comment
""" This is a multi-line
comment (docstring) """

# Indentation example
if True:
print("Indented block - this is inside if")
print("Same indentation = same block") print("This is
outside the if block")

Output:
Indented block - this is inside if
Same indentation = same block
This is outside the if block

Note: Python is case-sensitive: 'Name' and 'name' are different variables.

1.4 Variables & Data Types


A variable is a named storage location in memory. In Python, you do not need to declare the type of a
variable; it is automatically determined based on the value assigned.
name = "Alice" # str age
= 20 # int height =
5.6 # float is_student
= True # bool marks = 3 +
4j # complex

print(type(name)) #
print(type(age)) #
print(type(height)) #
print(type(is_student))#
print(type(marks)) #

Output:
Rules for Variable Names
• Must start with a letter or underscore (_)
• Cannot start with a digit
• Can contain letters, digits, and underscores
• Cannot be a Python keyword (if, for, while, etc.)
• Case-sensitive (myVar and myvar are different)

1.5 Type Casting


Type casting is the conversion of one data type into another. Python provides built-in functions for this
purpose.

# Implicit type conversion (automatic) x = 5


# int y = 2.5 # float z = x + y #
Python auto-converts x to float

print(z, type(z)) # 7.5

# Explicit type conversion (manual) a =


int(3.9) # 3 (truncates decimal) b =
float("4.5") # 4.5 c = str(100) #
'100' d = bool(0) # False e =
bool(42) # True f = int("101", 2) #
5 (binary to decimal)

print(a, b, c, d, e, f)

Output:
7.5
3 4.5 100 False True 5

1.6 Operators in Python


Category Operators Example

Arithmetic + - * / // % ** 5 + 3 = 8, 5 ** 2 = 25

Relational == != > < >= <= 5 > 3 → True

Logical and or not True and False → False

Assignment = += -= *= /= //= x += 5 is x = x + 5

Bitwise & | ^ ~ << >> 5&3→1

Identity is, is not x is y

Membership in, not in 'a' in 'apple' → True


# Operator examples x, y = 10, 3 print(x
// y) # 3 (floor division) print(x
% y) # 1 (modulus) print(x ** y)
# 1000 (exponent) print(x & y) #
2 (bitwise AND) print(10 in [10,20])#
True (membership) print(x is y) #
False (identity)

Output:
3
1
1000
2
True
False

1.7 Input / Output Functions


# input() always returns a string name = input("Enter
your name: ") age = int(input("Enter your age: "))
# cast to int print("Hello,", name, "! You are", age,
"years old.")

# print() formatting pi = 3.14159 print(f"Pi is approximately


{pi:.2f}") # f-string (recommended) print("Pi is approximately
{:.2f}".format(pi)) # .format() print("Pi is approximately %0.2f"
% pi) # % formatting

Output:
Hello, Alice ! You are 20 years old.
Pi is approximately 3.14
Pi is approximately 3.14
Pi is approximately 3.14

1.8 Control Structures


if / if-else / if-elif-else
marks = int(input("Enter marks: "))

if marks >= 90:


grade = "A+" elif
marks >= 80:
grade = "A" elif
marks >= 70:
grade = "B" elif
marks >= 60:
grade = "C"

elif marks >= 50:


grade = "D" else:
grade = "F"

print(f"Grade: {grade}")

# Nested if example num =


int(input("Enter a number: ")) if
num >= 0: if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
1.9 Looping in Python
for Loop
The for loop iterates over a sequence (list, tuple, string, range).
# Basic for loop with range
for i in range(1, 6):
print(i, end=" ") # Output:
1 2 3 4 5

# Iterating over a list fruits =


["apple", "banana", "cherry"] for
fruit in fruits: print(fruit)

# Nested for loop – multiplication table


for i in range(1, 4): for j in
range(1, 4):
print(i * j, end="\t")
print() # newline

Output: 1 2 3 4 5 apple banana cherry


1 2 3
2 4 6
3 6 9

while Loop
# while loop
n = 1 while n
<= 5:
print(n, end=" ")
n += 1 # Output: 1 2
3 4 5

# while with break and continue


i = 0 while True: i += 1
if i == 3:
continue # skip 3
if i == 6:
break # stop at 6
print(i, end=" ")
# Output: 1 2 4 5
Output:
1 2 3 4 5
1 2 4 5

Note: 'break' exits the loop immediately. 'continue' skips the current iteration and moves to the next. 'pass'
is a no-operation placeholder.
UNIT 2
Data Structures in Python
Strings • Lists • Tuples • Sets • Dictionaries • Comprehensions

2.1 Strings
A string is a sequence of characters enclosed in single, double, or triple quotes. Strings are immutable –
once created, they cannot be changed.
s = "Hello, Python!"

# Indexing (0-based) print(s[0]) # H print(s[-1]) # !

# Slicing [start:stop:step] print(s[0:5]) # Hello print(s[7:]) #


Python! print(s[::-1]) # !nohtyP ,olleH (reverse)

# String Methods print([Link]()) # HELLO, PYTHON! print([Link]())


# hello, python! print([Link]("Hello","Hi")) # Hi, Python! print([Link](",
")) # ['Hello', 'Python!'] print([Link]()) # removes whitespace
print(len(s)) # 14 print([Link]("He")) # True
print([Link]("l")) # 3 print("Py" in s) # True

# String Formatting name, age = "Alice", 20 print(f"Name: {name}, Age: {age}")


print("Name: {}, Age: {}".format(name, age))

Output:
H
!
Hello
Python!
!nohtyP ,olleH
HELLO, PYTHON!
hello, python!
Hi, Python!
['Hello', 'Python!']
Hello, Python!
14
True
3
True
Name: Alice, Age: 20
Name: Alice, Age: 20

2.2 Lists
A list is an ordered, mutable collection that can hold elements of different data types. Lists are defined
using square brackets [].
# Creating lists nums = [10, 20, 30, 40, 50] mixed =
[1, "hello", 3.14, True]

# Indexing and Slicing print(nums[0]) # 10


print(nums[-1]) # 50 print(nums[1:4]) # [20, 30,
40]

# List Methods [Link](60) # [10,20,30,40,50,60] [Link](2, 25)


# [10,20,25,30,40,50,60] [Link](25) # removes first occurrence
popped = [Link]() # removes & returns last element (60) [Link]()
# ascending sort [Link]() # reverse in place print([Link](30))
# 2 print([Link](20)) # 1 nums2 = [Link]() # shallow copy
[Link]([70, 80]) # add multiple items

# List Comprehension squares = [x**2 for x in range(1, 6)]


print(squares) # [1, 4, 9, 16, 25]

evens = [x for x in range(20) if x % 2 == 0] print(evens) # [0, 2, 4,


6, 8, 10, 12, 14, 16, 18]

Output:
10
50 [20, 30,
40]
2
1
[1, 4, 9, 16, 25]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
2.3 Tuples
A tuple is an ordered, immutable collection. Tuples are defined using parentheses (). They are faster
than lists and are used for data that should not change.
# Creating a tuple point = (3, 4) colors = ("red", "green",
"blue") single = (42,) # Note the trailing comma for single
element

# Indexing and Slicing print(colors[0])


# red print(colors[-1]) # blue
print(colors[0:2]) # ('red', 'green')

# Tuple methods
print([Link]("red")) # 1
print([Link]("green")) # 1

# Tuple unpacking x, y = point


print(f"x={x}, y={y}") # x=3, y=4

a, *b, c = (1, 2, 3, 4, 5)
print(a, b, c) # 1 [2, 3, 4] 5

# Tuple vs List t = (1, 2, 3) l = [1,


2, 3] # t[0] = 10 --> TypeError
(immutable) l[0] = 10 # OK
(mutable)

Output:
red blue ('red',
'green')
1 1 x=3,
y=4
1 [2, 3, 4] 5

2.4 Sets
A set is an unordered collection of unique elements. Sets do not allow duplicates. Defined using curly
braces {} or set() constructor.
# Creating sets a = {1, 2, 3, 4, 5} b
= {4, 5, 6, 7, 8}

# Set Operations

print(a | b) # Union: {1,2,3,4,5,6,7,8}


print(a & b) # Intersection: {4, 5} print(a -
b) # Difference: {1, 2, 3} print(a ^ b) #
Symmetric Diff: {1,2,3,6,7,8}

# Set Methods
[Link](6) # Add element
[Link](1) # Remove (no error if absent)
[Link](2) # Remove (error if absent)
print(len(a)) # 5

# Membership print(3 in
a) # True

# Remove duplicates from a list using set


lst = [1, 2, 2, 3, 3, 4] unique =
list(set(lst)) print(unique) # [1, 2,
3, 4]
Output: {1, 2, 3, 4, 5,
6, 7, 8}
{4, 5}
{1, 2, 3} {1, 2,
3, 6, 7, 8}
5
True
[1, 2, 3, 4]

2.5 Dictionaries
A dictionary is an unordered collection of key-value pairs. Keys must be unique and immutable. Values
can be of any type.
# Creating a dictionary student = {
"name" : "Alice",
"age" : 20,
"marks" : [85, 90, 78], "city" :
"Hyderabad"
}

# Accessing values print(student["name"]) # Alice


print([Link]("age")) # 20 print([Link]("phone", "N/A")) # N/A
(default if key missing)

# Modifying student["age"] = 21
student["phone"] = "9999999999"

# Dictionary methods print([Link]())


# dict_keys([...]) print([Link]()) #
dict_values([...]) print([Link]()) #
dict_items([...])

# Iterating for key, value in


[Link]():
print(f"{key}: {value}")

# Dictionary Comprehension squares = {x: x**2


for x in range(1, 6)} print(squares) # {1:1,
2:4, 3:9, 4:16, 5:25}

# Nested Dictionary college = { "EEE":


{"students": 60, "HOD": "Dr. Sharma"}, "CSE":
{"students": 120, "HOD": "Dr. Rao"} }
print(college["EEE"]["HOD"]) # Dr. Sharma
Output:
Alice
20 N/A name: Alice age: 21 marks: [85, 90,
78] {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Dr. Sharma

UNIT 3
Functions and Modules
Functions • Arguments • Scope • Lambda • map/filter/reduce • Recursion • Modules

3.1 Defining and Calling Functions


A function is a reusable block of code that performs a specific task. Functions help avoid code repetition,
improve readability, and make programs modular. Defined using the def keyword.
# Basic function definition and call def greet(name):
"""This function greets the person passed as parameter."""
print(f"Hello, {name}!")

greet("Alice") # Hello, Alice!


greet("Bob") # Hello, Bob!

# Function with return value


def add(a, b): return a
+ b

result = add(5, 3)
print(result) # 8

# Function with multiple return values


def min_max(lst): return min(lst),
max(lst)

lo, hi = min_max([4, 2, 9, 1, 7])


print(lo, hi) # 1 9
3.2 Types of Arguments
1. Positional Arguments
def describe(name, age, city): print(f"{name} is {age}
years old and lives in {city}.")

describe("Alice", 20, "Hyderabad")

2. Keyword Arguments
describe(age=20, city="Hyderabad", name="Alice") # order doesn't matter

3. Default Arguments
def power(base, exp=2): # exp has default value 2
return base ** exp

print(power(3)) # 9 (uses default exp=2)

print(power(3, 3)) # 27

4. Variable-Length Arguments (*args and **kwargs)


# *args – accepts any number of positional arguments (tuple)
def total(*args): return sum(args)

print(total(1, 2, 3)) # 6
print(total(10, 20, 30, 40)) # 100

# **kwargs – accepts any number of keyword arguments (dict)


def show_info(**kwargs): for key, value in
[Link](): print(f"{key} = {value}")

show_info(name="Alice", age=20, city="Hyd")

Output:
6 100 name = Alice age = 20 city = Hyd

3.3 Scope of Variables


The scope of a variable determines where in the program it is accessible. Python uses the LEGB rule:
Local → Enclosing → Global → Built-in.
x = "global" # Global scope

def outer(): x = "enclosing" #


Enclosing scope

def inner():
x = "local" # Local scope
print(x) # local

inner() print(x)
# enclosing

outer() print(x)
# global

# global keyword
count = 0

def increment():
global count
count += 1

increment() increment() print(count)


# 2

3.4 Lambda Functions


A lambda function is an anonymous (nameless) function defined in a single line. Syntax: lambda
arguments : expression. Useful for short, throwaway functions.
# Regular function vs lambda
def square(x): return x ** 2
sq = lambda x: x ** 2

print(square(5)) # 25
print(sq(5)) # 25

# Lambda with multiple arguments


add = lambda a, b: a + b
print(add(3, 4)) # 7

# Lambda with conditional is_even = lambda n:


"Even" if n % 2 == 0 else "Odd" print(is_even(4))
# Even print(is_even(7)) # Odd

3.5 map(), filter(), and reduce()


from functools import reduce

nums = [1, 2, 3, 4, 5]

# map(function, iterable) – applies function to each element


doubled = list(map(lambda x: x * 2, nums)) print(doubled)
# [2, 4, 6, 8, 10]

# filter(function, iterable) – keeps elements where function returns True


evens = list(filter(lambda x: x % 2 == 0, nums)) print(evens) #
[2, 4]

# reduce(function, iterable) – reduces to a single value


product = reduce(lambda x, y: x * y, nums)
print(product) # 120 (1*2*3*4*5)
3.6 Recursion
A function that calls itself is called a recursive function. Every recursive function must have a base case
that stops the recursion.
# Factorial using recursion def factorial(n):
if n == 0 or n == 1: # Base case return
1 return n * factorial(n - 1) # Recursive
call

print(factorial(5)) # 120

# Fibonacci using recursion


def fib(n): if n <= 1:
return n return fib(n-1) +
fib(n-2)

for i in range(8):
print(fib(i), end=" ")
# Output: 0 1 1 2 3 5 8 13

Output:
120
0 1 1 2 3 5 8 13

3.7 Modules
A module is a Python file containing functions, classes, and variables that can be reused across
programs.
# Importing modules
import math import
random import
datetime

# math module print([Link](16)) # 4.0


print([Link]) # 3.141592653589793
print([Link](4.2)) # 5
print([Link](5))# 120

# random module print([Link](1, 100)) # random


int between 1-100 print([Link](["a","b","c"])) #
random element lst = [1,2,3,4,5] [Link](lst)
print(lst)

# datetime module now =


[Link]()

print([Link]("%d-%m-%Y %H:%M:%S"))

# Creating your own module (save as [Link])


# def greet(name): # return f"Hello,
{name}!"
# # Then import
it:
# import mymodule
# print([Link]("Alice"))
Note: Use 'from module import function' to import specific items. Use 'import module as alias' for shorter
names (e.g., import numpy as np).
UNIT 4
File Handling and Exception Handling
File I/O • CSV & JSON • try/except/finally • Built-in Exceptions • Regular Expressions

4.1 File Handling


File handling allows Python programs to read from and write to files on disk. The built-in open() function is
used to open a file and returns a file object.
Mode Description

'r' Read (default). File must exist.

'w' Write. Creates new or truncates existing.

'a' Append. Adds to end of file.

'x' Exclusive create. Fails if file exists.

'b' Binary mode (use with r/w: 'rb', 'wb').

'+' Read and write ('r+', 'w+').


# Writing to a file with
open("[Link]", "w") as f:
[Link]("Hello, File!\n")
[Link]("Python is awesome.\n")
[Link](["Line 3\n", "Line 4\n"])

# Reading from a file with


open("[Link]", "r") as f:
content = [Link]() # read entire file
print(content)

with open("[Link]", "r") as f:


lines = [Link]() # list of lines
print(lines)

with open("[Link]", "r") as f:


for line in f: # line by line
print([Link]())

# Appending to a file with


open("[Link]", "a") as f:
[Link]("Appended line\n")

# File methods with


open("[Link]", "r") as f:
print([Link]()) # current position
[Link](0) # move to start
Output:
Hello, File!
Python is awesome.
Line 3
Line 4

Note: Always use 'with' statement (context manager) when working with files. It automatically closes the file
even if an error occurs.

4.2 Working with CSV Files


import csv

# Writing a CSV file with open("[Link]",


"w", newline="") as f:
writer = [Link](f) [Link](["Name",
"Age", "Marks"]) # header
[Link](["Alice", 20, 85])
[Link](["Bob", 21, 90])
[Link](["Carol", 20, 78])

# Reading a CSV file with


open("[Link]", "r") as f:
reader = [Link](f)
for row in reader:
print(row)

# Using DictReader / DictWriter with


open("[Link]", "r") as f:
reader = [Link](f)
for row in reader:
print(f"{row['Name']}: {row['Marks']}")
4.3 Working with JSON Files
import json

# Python dict to JSON file data = {"name": "Alice", "age":


20, "marks": [85, 90, 78]}

with open("[Link]", "w") as f: [Link](data, f,


indent=4) # write with indentation

# JSON file to Python dict with


open("[Link]", "r") as f:
loaded = [Link](f)
print(loaded["name"]) # Alice
print(loaded["marks"]) # [85, 90, 78]

# String conversions json_str = [Link](data)


# dict -> JSON string print(json_str)
py_dict = [Link](json_str) # JSON string -> dict
print(type(py_dict)) #

4.4 Exception Handling


An exception is an error that occurs during program execution. Python provides a try-except block to
catch and handle exceptions gracefully, preventing program crashes.
# Basic try-except
try:
x = int(input("Enter a number: "))
result = 10 / x print(f"Result:
{result}") except ValueError:
print("Error: Please enter a valid integer!")
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except Exception as e:
print(f"An unexpected error occurred: {e}")
else:
print("No exception occurred!") # runs if no exception
finally:
print("This always executes.") # runs regardless

Output:
(if user enters 0) Error:
Cannot divide by zero!
This always executes.

(if user enters 5)


Result: 2.0 No
exception occurred!
This always executes.
Raising Exceptions
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
if age > 150:
raise ValueError("Age seems unrealistic!")
return f"Valid age: {age}"
try:
print(validate_age(-5)) except
ValueError as e: print(e) # Age
cannot be negative!

# Custom Exception class


InsufficientFundsError(Exception):
def __init__(self, balance, amount):
[Link] = balance [Link] = amount
super().__init__(f"Cannot withdraw {amount}. Balance: {balance}")
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(balance, amount)
return balance - amount

try:
withdraw(500, 1000) except
InsufficientFundsError as e:
print(e)
4.5 Regular Expressions (re module)
Regular expressions are patterns used to match, search, and manipulate strings. Python's re module
provides regular expression support.
import re

text = "Contact us at support@[Link] or sales@[Link]"

# [Link] – find all matches emails = [Link](r'[\w.-]


+@[\w.-]+\.\w+', text) print(emails) #
['support@[Link]', 'sales@[Link]']

# [Link] – find first match m = [Link](r'\d+',


"Order 1234 placed on 05-12-2024") print([Link]()) #
1234

# [Link] – match at beginning of string


m = [Link](r'Hello', "Hello World")
print([Link]()) # Hello

# [Link] – replace matches result = [Link](r'\d+', 'NUM',


"I have 3 cats and 2 dogs") print(result) # I have NUM
cats and NUM dogs
# [Link] parts = [Link](r'[,;\s]+', "one, two;
three four") print(parts) # ['one', 'two',
'three', 'four']

Output: ['support@[Link]',
'sales@[Link]']
1234
Hello
I have NUM cats and NUM dogs
['one', 'two', 'three', 'four']
UNIT 5
Object-Oriented Programming and Applications
Classes • Objects • Inheritance • Encapsulation • Polymorphism • Applications

5.1 OOP Concepts Overview


Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects, which
contain data (attributes) and code (methods). The four pillars of OOP are:
• Encapsulation: Bundling data and methods inside a class; hiding internal details.
• Abstraction: Exposing only essential features, hiding implementation details.
• Inheritance: A class (child) can inherit attributes and methods from another class (parent).
• Polymorphism: The same method name behaves differently in different classes.

5.2 Classes and Objects


# Defining a class class Student: # Class
variable (shared by all instances) college
= "MLR Institute of Technology"

# Constructor (__init__ is called when object is created)


def __init__(self, name, roll, marks): # Instance
variables [Link] = name [Link] = roll
[Link] = marks

# Instance method
def display(self):
print(f"Roll: {[Link]}, Name: {[Link]}, Marks: {[Link]}")

def grade(self):
if [Link] >= 90: return "A+"
elif [Link] >= 80: return "A"
elif [Link] >= 70: return "B"
else: return "C"

# String representation def __str__(self):


return f"Student({[Link]}, {[Link]})"

# Creating objects (instances) s1 =


Student("Alice", "21EE001", 87) s2 =
Student("Bob", "21EE002", 72)
[Link]() # Roll: 21EE001, Name: Alice, Marks: 87
print([Link]()) # A print([Link])# MLR
Institute of Technology print(s1) #
Student(Alice, 21EE001)

5.3 Inheritance
Inheritance allows a child class to inherit attributes and methods from a parent class, promoting code
reusability.

1. Single Inheritance
class Animal: def
__init__(self, name):
[Link] = name def
speak(self): print(f"{[Link]}
makes a sound.")

class Dog(Animal): # Dog inherits from Animal


def speak(self): # Method Overriding
print(f"{[Link]} says: Woof!") def
fetch(self): print(f"{[Link]}
fetches the ball.")

d = Dog("Rex")
[Link]() # Rex says: Woof!
[Link]() # Rex fetches the ball.
print(isinstance(d, Animal)) # True

2. Multiple Inheritance
class Father:
def skill1(self): print("Father: Farming")

class Mother: def skill2(self):


print("Mother: Cooking")

class Child(Father, Mother): # inherits from both


def skill3(self): print("Child: Coding")

c = Child()
c.skill1() # Father: Farming
c.skill2() # Mother: Cooking
c.skill3() # Child: Coding
3. Multilevel Inheritance
class Vehicle: def move(self): print("Vehicle
moves")

class Car(Vehicle):

def fuel(self): print("Car uses petrol")


class ElectricCar(Car): # ElectricCar inherits Car which inherits Vehicle
def battery(self): print("ElectricCar has battery")

ec = ElectricCar() [Link]() #
Vehicle moves [Link]() # Car uses
petrol [Link]() # ElectricCar has
battery

# super() – calling parent class methods


class Animal: def __init__(self,
name): [Link] = name

class Cat(Animal):
def __init__(self, name, color):
super().__init__(name) # call Animal's __init__
[Link] = color

c = Cat("Whiskers", "white")
print([Link], [Link]) # Whiskers white

5.4 Encapsulation
class BankAccount: def __init__(self, owner, balance):
[Link] = owner # public self._pin =
"1234" # protected (convention) self.__balance
= balance # private (name mangling)

def deposit(self, amount):


if amount > 0:
self.__balance += amount print(f"Deposited
{amount}. Balance: {self.__balance}")

def withdraw(self, amount):


if amount > self.__balance:
print("Insufficient funds!")
else:
self.__balance -= amount print(f"Withdrawn
{amount}. Balance: {self.__balance}")

def get_balance(self): # getter


return self.__balance

acc = BankAccount("Alice", 5000) [Link](1000)


# Deposited 1000. Balance: 6000

[Link](2000) # Withdrawn 2000. Balance: 4000


print(acc.get_balance()) # 4000 #
print(acc.__balance) # AttributeError (private)
5.5 Polymorphism
# Method Overriding (Runtime Polymorphism)
class Shape: def area(self):
return 0

class Circle(Shape):
def __init__(self, r): self.r = r def
area(self): return 3.14 * self.r ** 2

class Rectangle(Shape):
def __init__(self, l, w): self.l, self.w = l, w
def area(self): return self.l * self.w

class Triangle(Shape):
def __init__(self, b, h): self.b, self.h = b, h
def area(self): return 0.5 * self.b * self.h

shapes = [Circle(5), Rectangle(4, 6), Triangle(3, 8)]


for s in shapes: print(f"{s.__class__.__name__}:
Area = {[Link]()}")

# Duck Typing (Python's natural polymorphism)


class Dog:
def sound(self): return "Woof"

class Cat: def sound(self):


return "Meow"

def make_sound(animal):
print([Link]())

make_sound(Dog()) # Woof
make_sound(Cat()) # Meow

Output:
Circle: Area = 78.5
Rectangle: Area = 24
Triangle: Area = 12.0
Woof
Meow

5.6 Application: Simple Calculator


class Calculator: """A simple calculator
application using OOP."""

def add(self, a, b): return a + b def


subtract(self, a, b): return a - b def multiply(self, a,
b): return a * b def divide(self, a, b): if b ==
0: raise ZeroDivisionError("Cannot divide by
zero!") return a / b def power(self, a, b):
return a ** b def modulus(self, a, b): return a % b

calc = Calculator()

while True:
print("\n--- Simple Calculator ---") print("[Link]
[Link] [Link] [Link] [Link] [Link]") choice =
input("Choose: ") if choice == '6':
break a = float(input("Enter
first number: ")) b = float(input("Enter
second number: ")) try:
if choice == '1': print("Result:", [Link](a, b))
elif choice == '2': print("Result:", [Link](a, b))
elif choice == '3': print("Result:", [Link](a, b))
elif choice == '4': print("Result:", [Link](a, b))
elif choice == '5': print("Result:", [Link](a, b)) except
ZeroDivisionError as e:
print(e)

5.7 Application: Data Processing with pandas


import pandas as pd

# Creating a DataFrame data = { "Name" :


["Alice", "Bob", "Carol", "David"],
"Age" : [20, 21, 20, 22],
"Marks" : [85, 72, 90, 65], "City"
: ["Hyd", "Hyd", "Pune", "Hyd"] } df =
[Link](data)

print(df) print("\nBasic
Statistics:")

print([Link]())

# Filtering hyderabad =
df[df["City"] == "Hyd"] print("\
nStudents from Hyderabad:")
print(hyderabad)

# Sorting sorted_df = df.sort_values("Marks",


ascending=False) print("\nSorted by Marks:")
print(sorted_df)
# Adding new column df["Grade"] = df["Marks"].apply(
lambda m: "A+" if m>=90 else ("A" if m>=80 else "B") )
print("\nWith Grade column:") print(df)

# Saving to CSV
df.to_csv("student_report.csv", index=False)

END OF NOTES — Python Programming | I [Link] II Sem | R25 | MLR Institute of Technology

You might also like