0% found this document useful (0 votes)
4 views

Balc python notes

The document provides a comprehensive overview of Python basics for beginners, covering essential concepts such as print statements, variables, data types, operators, conditional statements, lists, tuples, and dictionaries. It includes examples and explanations of how to use these features effectively in Python programming. Additionally, it highlights important points regarding user input and string operations.

Uploaded by

tendercutter
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Balc python notes

The document provides a comprehensive overview of Python basics for beginners, covering essential concepts such as print statements, variables, data types, operators, conditional statements, lists, tuples, and dictionaries. It includes examples and explanations of how to use these features effectively in Python programming. Additionally, it highlights important points regarding user input and string operations.

Uploaded by

tendercutter
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Python Basics: Essential Concepts for Beginners

Print Statement:
print("Hello, World!")
Printing on a New Line Using \n
e.g print("Hello\nWorld")
Printing Counting
e.g print(1, 2, 3, 4, 5)

Variables:
A variable is used to store data in Python.
A variable name can only have letters, numbers, and underscores (_).
e.g
name = "Ali"
age_1 = 25
Types of Variables:
integer (int) – Stores Whole Numbers
age = 25
price = 1000
Float (float) – Stores Decimal Numbers
height = 5.8
temperature = 36.5
String (str) – Stores Text
name = "Iqra Afzal"
city = 'Lahore'
Boolean (bool) – Stores True or False
Student = True
Teacher = False
Keywords in Python:
Keywords are special words in Python that have a fixed meaning and cannot be used as
variable names. Python has 33 keywords (in Python 3) that are used to perform specific tasks.
Keywords Keywords Keywords Keywords
False None True And
As Assert async Await
Break Class continue Def
Del Elif else Except
Finally For from Global
If Import in Is
Lambda Nonlocal not Or

1
Pass Raise return Try
While With yield

Arithmetic operators:
Addition (+):
used with integers, floats, and even strings.
e.g:
print(5 + 3) # Output: 8
print(2.5 + 1.5) # Output: 4.0
print("Hello " + "World") # Output: Hello World
Subtraction (-):
Used to subtract one number from another.
e.g:
print(10 - 4) # Output: 6
print(7.5 - 2.5) # Output: 5.0
Multiplication (*):
Used to multiply numbers.
Can also repeat a string.
e.g:
print(6 * 3) # Output: 18
print(2.5 * 2) # Output: 5.0
print("Hello " * 3) # Output: Hello Hello Hello
Division (/ and //):
/ gives a float result.
// (floor division) removes decimal places and gives an integer result.
e.g:
print(10 / 3) # Output: 3.3333
print(10 // 3) # Output: 3
Modulus (%)
Returns the remainder of division.
e.g:
print(10 % 3) # Output: 1
print(15 % 4) # Output: 3
Exponentiation ( or pow())**:
Raises one number to the power of another.
e.g:
2
print(2 ** 3) # Output: 8
print(pow(3, 2)) # Output: 9

Relational (comparison) operators:


Operator Meaning Example Output
== Equal to 5 == 5 True
!= Not equal to 5!=3 True
> Greater Than 7>5 True
< Less Than 3<8 True
Greater-than OR
>= 6>=6 True
Equal to
Less-than OR
<= 4<=9 True
Equal to

Assignment operators:
Operator Meaning Example
= Assigns a value to a variable X = 10
X + = 3#
+= Adds and assigns Same as
X=X+3
y – = 4#
-= Subtract and Assigns Same as
y=y–4
Z * = 2#
*= Multiplies and Assigns Same as
Z=Z*2
a / = 5#
/= Divides and Assigns Same as
a=a/5
b //= 2 #
%= Floor divides and assigns Same as
b = b //2
c %= 5 #
**= Modulus and assigns Same as
c=c%5
d **= 2 #
Exponentiates and assigns Same as
d = d ** 2
3
Logical Operators:
Operator Meaning Example
Returns True if both conditions (5 > 2) and (10 > 3) #
And
are true True
Returns True if at least one (5 > 2) or (10 < 3) #
or
condition is true True
Reverses the result (True →
not not (5 > 2) # False
False, False → True)

Types of conversion:
Type conversion means changing one data type into another. There are two types:
Implicit Conversion (Automatic):
➢ Python automatically changes one type to another when it is safe.
e.g:
x=5 # Integer
y = 2.5 # Float
Explicit Conversion (Manual Type Casting):
➢ You decide which type to convert using functions like int(), float(), str(), etc.
e.g:
price = 99.99 # Float
new_price = int(price) # Convert to Integer (removes decimal)
print(new_price) # Output: 99
Input statement:
The input() function is used to take user input in Python. It allows the user to enter data,
which can then be stored in a variable and used in the program.
Basic Syntax:
variable_name = input("Enter your message: ")
Taking User Input (String)
name = input("Enter your name: ")
print("Hello, " + name + "!")
The program prints: "Hello, Noor!"
Taking Numeric Input (Integer)
4
age = input("Enter your age: ")
age = int(age) # Convert string to integer
print(“you will be” + age + “next year!”)
The program prints: "You will be 21 next year!").
Taking Float Input
price = float(input("Enter the product price: "))
discounted_price = price - 10 # Subtracting discount
print("Discounted price: ", discounted_price)

Important Points to Remember:


input() always returns string data by default.
Use int() or float() to convert the input if needed.
The message inside input("message") is optional but helps the user understand what
to enter.

String in python:
A string is a collection of characters (letters, numbers, symbols) enclosed in quotes. In
Python, strings are immutable, meaning you cannot change them after creating them.
String Operations:
1. Concatenation (Joining Strings)
You can combine two or more strings using the + operator.
first_name = "Noor"
last_name = "Fatima"
full_name = first_name + " " + last_name
print(full_name) # Output: Noor Fatima
2. Repeating Strings
Use * to repeat a string multiple times.
text = "Hello! " * 3
print(text) # Output: Hello! Hello! Hello!
3. String Indexing (Accessing Characters)
Each character in a string has a position (index), starting from 0.
Positive Indexing:
word = "Python"
P Y T H O N
0 1 2 3 4 5
print(word[0]) # Output: P (First letter)
5
Negative Indexing:
word = "Python"
P Y T H O N
-6 -5 -4 -3 -2 -1
print(word[-1]) # Output: n (Last letter)
4. String Slicing (Extracting Part of a String)
Use : to get a part of a string.
word = "Programming"
print(word[0:4]) # Output: Prog
print(word[:6]) # Output: Progra
print(word[4:]) # Output: ramming
print(word[-8:-3]) # Output: gramm
5. Finding the Length of a String
Use len() to count the number of characters in a string.
message = "Python is fun!"
print(len(message)) # Output: 14
String functions:
Python provides built-in string methods that help in modifying and handling strings
easily.
1. Changing Case
(a) Convert to Uppercase (.upper())
Converts all letters in the string to uppercase.
text = "hello world"
print(text.upper()) # Output: HELLO WORLD
(b) Convert to Lowercase (.lower())
Converts all letters to lowercase.
text = "HELLO WORLD"
print(text.lower()) # Output: hello world
(c) Capitalize First Letter (.capitalize())
Makes the first letter uppercase and the rest lowercase.
text = "hello world"
print(text.capitalize()) # Output: Hello world
3. Finding and Replacing
(a) Find a word in a string (.find())
Returns the index where the word starts (or -1 if not found).
text = "I love programming"
print(text.find("love")) # Output: 2
6
(b) Replace a word (.replace())
text = "I love Python"
print(text.replace("Python", "Java")) # Output: I love Java

Conditional statements:
Conditional statements in Python help us make decisions in our programs based on
conditions.
If – elif – else
1. if Statement
if statement executes a block of code only if the condition is True.
age = 18
if age >= 18:
print("You are eligible to vote.")
2. if-else Statement
If the condition is True, the if block runs; otherwise, the else block runs.
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
3. if-elif-else Statement
The elif (else if) statement is used when we have multiple conditions to check.
marks = 75
if marks >= 90:
print("Grade: A")
elif marks >= 80:
print("Grade: B")
elif marks >= 70:
print("Grade: C")
else:
print("Grade: D")
4. Nested if Statement
An if statement inside another if statement is called a nested if statement.
num = 10
if num > 0:
print("Positive number")
if num % 2 == 0:
print("Even number")
7
List in python:
A list is a collection of multiple values stored in a single variable.
Lists are ordered, mutable (changeable), and allow duplicate values.
Creating a List
A list is created using square brackets [ ], and items are separated by commas.
fruits = ["Apple", "Banana", "Mango", "Orange"]
numbers = [1, 2, 3, 4, 5]
mixed = ["Hello", 10, 5.5, True] # A list can contain different data types
Accessing List Items
You can access list items using indexing (starting from 0 for the first item).
fruits = ["Apple", "Banana", "Mango", "Orange"]
print(fruits[0]) # Apple
print(fruits[2]) # Mango
Negative Indexing:
-1 refers to the last item, -2 to the second last, and so on.
print(fruits[-1]) # Orange
print(fruits[-2]) # Mango
Modifying List Items
Lists are mutable, meaning we can change their elements.
fruits[1] = "Grapes"
print(fruits) # ['Apple', 'Grapes', 'Mango', 'Orange']
List slicing:
You can access a portion of a list using slicing.
fruits = ["Apple", "Banana", "Mango", "Orange", "Peach"]
print(fruits[1:4]) # ['Banana', 'Mango', 'Orange']
print(fruits[:3]) # ['Apple', 'Banana', 'Mango']
print(fruits[2:]) # ['Mango', 'Orange', 'Peach']

List Methods:
1. append() – Add an item at the end
fruits = ["Apple", "Banana"]
fruits.append("Mango")
print(fruits) # ['Apple', 'Banana', 'Mango']
2. insert() – Insert an item at a specific index
fruits.insert(1, "Grapes")
print(fruits) # ['Apple', 'Grapes', 'Banana']
3. extend() – Add multiple items at the end
8
fruits.extend(["Peach", "Orange"])
print(fruits) # ['Apple', 'Banana', 'Peach', 'Orange']
4. remove() – Remove a specific item
fruits.remove("Banana")
print(fruits) # ['Apple', 'Peach', 'Orange']
5. pop() – Remove an item by index (default is last item)
fruits.pop(1)
print(fruits) # ['Apple', 'Orange']
6. clear() – Remove all items from the list
fruits.clear()
print(fruits) # []
7. index() – Find the index of an item
fruits = ["Apple", "Banana", "Mango"]
print(fruits.index("Banana")) # 1
8. count() – Count occurrences of an item
numbers = [1, 2, 3, 2, 2, 4]
print(numbers.count(2)) # 3
9. sort() – Sort the list in ascending order
numbers = [4, 1, 7, 3]
numbers.sort()
print(numbers) # [1, 3, 4, 7]
Sort in descending order
numbers.sort(reverse=True)
print(numbers) # [7, 4, 3, 1]
10. reverse() – Reverse the order of the list
fruits = ["Apple", "Banana", "Mango"]
fruits.reverse()
print(fruits) # ['Mango', 'Banana', 'Apple']

Tuples in Python:
A tuple is a collection of items that is ordered and immutable (cannot be changed after
creation). Tuples are similar to lists, but they use parentheses () instead of square brackets
[].
1. Creating a Tuple
fruits = ("Apple", "Banana", "Mango")
print(fruits) # ('Apple', 'Banana', 'Mango')
2. Accessing Elements in a Tuple
Tuples support indexing like lists.
9
fruits = ("Apple", "Banana", "Mango")
print(fruits[0]) # Apple
print(fruits[-1]) # Mango
3. Slicing a Tuple
numbers = (1, 2, 3, 4, 5)
print(numbers[1:4]) # (2, 3, 4)
print(numbers[:3]) # (1, 2, 3)
print(numbers[::2]) # (1, 3, 5)
Tuples Method:
1. count() Method
This method tells how many times a value appears in the tuple.
numbers = (1, 2, 3, 2, 4, 2)
print(numbers.count(2)) # Output: 3
2. index() Method
This method gives the position (index) of the first occurrence of a value.
fruits = ("Apple", "Banana", "Mango", "Banana")
print(fruits.index("Banana")) # Output: 1 (first Banana at index 1)
Dictionary in Python:
Dictionaries are used to store data values in key:value pairs “key” : value
They are unordered, mutable(changeable) & don’t allow duplicate keys.
Dictionaries use curly brackets {} and store data in key: value format.
1. Creating a Dictionary
student = {
"name": "Aisha",
"age": 20,
"grade": "A"}
print(student)
2. Adding and Updating Values
student["city"] = "Lahore"
print(student)
# {'name': 'Aisha', 'age': 20, 'grade': 'A', 'city': 'Lahore'}
3. Removing Key-Value Pairs
student.pop("grade")
print(student)
# {'name': 'Aisha', 'age': 21, 'city': 'Lahore'}
4. Remove all items (clear())
student.clear()
10
print(student) # Output: {}
Nested Dictionaries:
(Dictionary inside Dictionary)
school = {
"student1": {"name": "Aisha", "age": 20},
"student2": {"name": "Ali", "age": 22}
}
print(school["student1"]["name"]) # Output: Aisha
Dictionary Methods:
Operator Meaning Example
keys() Returns all dictionary keys student.keys()
Returns all dictionary
values() student.values()
values
Returns key-value pairs as
items() student.items()
tuples
Updates dictionary with student.update({"grade":
update()
new values "A+"})

Set in Python:
Set is the collection of the unordered items. Each element in the set must be unique &
immutable. It does not allow duplicate values and uses curly brackets {}.
fruits = {"Apple", "Banana", "Mango"}
print(fruits)
Sets in Python
A set is a collection of unique and unordered elements. It does not allow duplicate values
and uses curly brackets {}.
1. Creating a Set
fruits = {"Apple", "Banana", "Mango"}
print(fruits)
⚠ Note: The order of elements may change because sets are unordered.
2. No Duplicates in Sets
If you add duplicate values, they will be removed automatically.
numbers = {1, 2, 2, 3, 4, 4, 5}
print(numbers) # Output: {1, 2, 3, 4, 5}
3. Adding and Removing Elements
Add a single element (add())

11
fruits = {"Apple", "Banana"}
fruits.add("Mango")
print(fruits) # {'Apple', 'Banana', 'Mango'}
Add multiple elements (update())
fruits = {"Apple", "Banana"}
fruits.update(["Mango", "Orange"])
print(fruits) # {'Apple', 'Banana', 'Mango', 'Orange'}
Remove an element (remove() or discard())
fruits = {"Apple", "Banana", "Mango"}
fruits.remove("Banana")
print(fruits) # {'Apple', 'Mango'}
Remove a random element (pop())
fruits = {"Apple", "Banana", "Mango"}
fruits.pop() # Removes a random element
print(fruits)
Clear all elements (clear())
fruits.clear() # Set becomes empty
print(fruits) # Output: set()
5. Set Operations
Operator Description Example
Combines two sets
union() A.union(B)
(without duplicates).
Finds common elements in
intersection() A.intersection(B)
two sets.

Loops in Python:
Loops are used to repeat instructions. Loops are used used for sequential traversal. For
traversing list, string, tuples etc.
While loops:
A while loop runs as long as the condition is True.
i=1
while i <= 5:
print(i)
i += 1 # Increment i
for Loops:
for i in range(1, 6): # Iterates from 1 to 5

12
print(i)
for Loop with else:
for i in range(1, 4):
print(i)
else:
print("Loop completed successfully!")
Break & Continue
Break :
Used to terminate the loop when encountered.
i=1
while i <= 10:
if i == 5:
break # Stops the loop when i is 5
print(i)
i += 1
Continue :
terminates execution in the current iteration & continues execution of the loop with the
next iteration.
i=0
while i < 5:
i += 1
if i == 3:
continue # Skips printing 3
print(i)

Range( ):
Range functions returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and stops before a specified number.
range( ) range( start?, stop, step?)
for i in range(1, 6):
# Prints numbers from 1 to 5
print(i)

pass Statement:
pass is a null statement that does nothing. It is used as a placeholder for future code.
for i in range(5):
if i == 3:

13
pass # This does nothing
print(i)

Functions in Python:
A function is a block of reusable code that performs a specific task. Instead of writing the
same code again and again, we use functions to make our code organized, reusable, and
easy to manage.
def greet():
print("Hello, Welcome to Python!")
greet()
Hello, Welcome to Python

File I/O in Python:


File handling allows us to read, write, and modify files stored on our computer using
Types of all files:
Text Files: .txt, .docx, .log etc.
Binary Files: .mp4, .mov, .png, .jpeg etc.
Opening a File:
We have to open a file before reading or writing.
To open a file, we use the open() function.
File = open("example.txt", "r") # Opens a file in read mode
The open() function has two arguments:
File Name → "example.txt" (the name of the file to open).
Mode → "r" (tells Python how to open the file).
Different Modes of Opening a File:
Mode Description
“r” Read mode (default). Opens a file for reading. Gives an error if the file does
not exist.
“w” Write mode. Creates a new file or overwrites the existing file content.
“a” Append mode. Adds new data without removing old content. Creates a
new file if it doesn't exist.
“x” Exclusive creation mode. Creates a new file but gives an error if the file
already exists.

14
“r+” Read and write mode. Does not create a new file if it doesn’t exist.
“w+” Write and read mode. Overwrites the existing file or creates a new file.
“a+” Append and read mode. Keeps old content and allows adding new data.
“rb” Read mode for binary files (like images, audio, etc.).

“wb” Write mode for binary files (creates or overwrites a file).


“ab” Append mode for binary files (keeps old data and adds new)
“rb+” Read and write mode for binary files.
“wb+” Write and read mode for binary files.
“ab+” Append and read mode for binary files.
Reading a File
Python provides multiple ways to read files.
Reading the Entire File
file = open("example.txt", "r") # Open file in read mode
content = file.read() # Read full content
print(content) # Print file content
file.close() # Close the file after reading
Reading a Specific Number of Characters
file = open("example.txt", "r")
print(file.read(5)) # Reads first 5 characters only
file.close()
Reading Line by Line
file = open("example.txt", "r")
print(file.readline()) # Reads only the first line
file.close()
Reading All Lines as a List
file = open("example.txt", "r")
lines = file.readlines() # Reads all lines and stores them in a list
print(lines) # Each line is stored as a list element
15
file.close()
Writing to a File
We use "w" (write mode) or "a" (append mode) to write data to a file.
Writing to a File (Overwriting Content)
file = open("example.txt", "w") # Open file in write mode
file.write("Hello, Python!") # Overwrites existing content
file.close()
Note: This deletes old content and replaces it with new content.
Appending to a File (Keeping Old Content & Adding New)
file = open("example.txt", "a") # Open file in append mode
file.write("\nThis is a new line!") # Adds new data without removing old content
file.close()
Using with Statement (Recommended Way)
Instead of open() and close(), the with statement automatically closes the file.
Reading a File with with Statement
with open("example.txt", "r") as file:
content = file.read()
print(content) # No need to manually close the file
Writing to a File with with Statement
with open("example.txt", "w") as file:
file.write("Learning Python is fun!") # File is automatically closed
Checking if a File Exists
Before reading or deleting a file, it's good to check if it exists.
import os
if os.path.exists("example.txt"):
print("File exists")
else:
16
print("File not found")
Deleting a File
If you no longer need a file, you can delete it using os.remove().
import os
os.remove("example.txt") # Deletes the file permanently
Note: Make sure to check if the file exists before deleting it.
Working with Binary Files (Images, Audio, etc.)
For non-text files (like images, videos, etc.), we use binary mode (b).
Reading a Binary File (e.g., an Image)
with open("image.jpg", "rb") as file:
data = file.read()
print(data) # Prints binary content
Writing a Binary File
with open("new_image.jpg", "wb") as file:
file.write(data) # Writing binary data

Object-Oriented Programming (OOP) in Python:


OOP is a way of writing programs where we organize code using objects.
An object is something that has properties (data) and actions (functions).
Python allows us to create objects using classes.
Class and Object
A class is like a template that defines how an object should behave. An object is a
copy of that class with actual values.
#creating class
class Student: name = “iqra Afzal”
#creating object (instance)
s1 = Student( ) print( s1.name ) A

17
Constructor (__init__ Method):
The __init__ method is a special function that runs automatically when an object
is created. It helps initialize variables inside the object.
class Student:
def __init__(self, name, age):
print("loading…..") # Fixed indentation
self.name = name
self.age = age
#Creating an object outside the class
s1 = Student("Noor", 20)
print(s1.name) # Correct
print(s1.age) # Fixed: s1 instead of s2
Class & Instance Attributes:
Class Attributes
Instance Attributes
Class Attributes
• These belong to the class and are shared by all objects.
• They are defined inside the class but outside any method.
• You can access them using the class name or any object.
Example:
class Student:
school = "ABC School" # Class attribute
print(Student.school) # Accessing directly from class
s1 = Student()
print(s1.school) # Accessing from an object
Instance Attributes
• These belong to individual objects and are not shared.
18
• They are defined inside the __init__ method using self.
• Each object has its own copy of instance attributes.
Example:
Class Student:
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute
s1 = Student("Noor", 20)
s2 = Student("Aisha", 22)
print(s1.name, s1.age) # Noor 20
print(s2.name, s2.age) # Aisha 22
Key Difference
• Class attributes → Shared by all objects.
• Instance attributes → Unique for each object.
Methods:
A method is a function that belongs to a class. It is used to perform actions on
objects.
Types of Methods in Python
1. Instance Methods
• The most common type of method.
• Works with instance attributes.
• Uses self as the first parameter.
Example:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
19
def show_details(self): # Instance method
print(f"Name: {self.name}, Age: {self.age}")
s1 = Student("Noor", 20)
s1.show_details() # Output: Name: Noor, Age: 20
2. Static Methods
• Does not depend on class or instance attributes.
• Uses @staticmethod decorator.
• Works like a normal function inside a class.
Example:
class Math:
@staticmethod
def add(a, b):
return a + b
print(Math.add(5, 3)) # Output: 8
Class Method
A class method is a method that belongs to the class rather than an instance
(object). It is defined using the @classmethod decorator and takes cls as its
first parameter instead of self.
Example of a Class Method
class Student:
school_name = "ABC School" # Class Attribute
@classmethod
def change_school(cls, new_name):
cls.school_name = new_name # Modifies class attribute
# Calling class method without creating an object
Student.change_school("XYZ School")
print(Student.school_name) # Output: XYZ School
20
@property in Python:
@property decorator in Python is used to define a method as a property.
It allows us to access a method like an attribute (without parentheses ()),
making the code cleaner.
Example of @property
class Student:
def __init__(self, name, marks):
self.name = name
self._marks = marks # Private attribute (single underscore)
@property
def percentage(self):
return (self._marks / 500) * 100 # Convert marks to percentage
# Creating an object
s = Student("Noor", 400)
# Accessing method like an attribute (without parentheses)
print(s.percentage) # Output: 80.0
Abstraction in Python:
Abstraction means hiding unnecessary details and showing only important
information. It helps in making code simple and easy to use.
Example
class Car:
def __init__(self, name, age):
self.name = name
self.age = age
self.acc = False
self.brk = False
self.clutch = False
21
def start(self):
self.clutch = True
self.acc = True
print("Car started") # Fixed print statement
Encapsulation in Python:
Encapsulation means hiding the data and only allowing controlled access to it
using methods.
Example
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner # Public attribute
self.__balance = balance # Private attribute (cannot be accessed directly)
def deposit(self, amount):
self.__balance += amount
print("Deposited {amount}. New balance: {self.__balance}")
def withdraw(self, amount):
if amount > self.__balance:
print("Insufficient balance!")
else:
self.__balance -= amount
print(f"Withdrawn {amount}. Remaining balance: {self.__balance}")
def get_balance(self): # Getter method to access private variable
return self.__balance
# Creating an object
account = BankAccount("Noor", 1000)
# Accessing Public Attribute
print(account.owner) # Output: Noor
22
print(account.get_balance()) # Output: 1000
# Depositing money
account.deposit(500) # Output: Deposited 500. New balance: 1500
# Withdrawing money
account.withdraw(200) # Output: Withdrawn 200. Remaining balance: 1300
Inheritance in Python:
Inheritance means one class (child class) can use the properties and methods
of another class (parent class). It helps reuse code and makes programming easier.
Example of Inheritance
class Parent:
def greet(self):
print("Hello from Parent class")
class Child(Parent): # Child class inherits Parent class
pass
c = Child()
c.greet() # Child class can use Parent class method
Types of Inheritance:
Inheritance allows one class to use the properties and methods of another class.
There are five types of inheritance in Python.
1. Single Inheritance (One Parent → One Child)
A child class inherits from one parent class.
class Parent:
def show(self):
print("This is the Parent class")
class Child(Parent):
pass
c = Child()
23
c.show() # Child can use Parent's method
2. Multiple Inheritance (One Child → Multiple Parents)
A child class inherits from two or more parent classes.
class Parent1:
def show1(self):
print("This is Parent 1")
class Parent2:
def show2(self):
print("This is Parent 2")
class Child(Parent1, Parent2):
pass
c = Child()
c.show1() # Inherited from Parent1
c.show2() # Inherited from Parent2
3. Multi level Inheritance (Grandparent → Parent → Child)
A child class inherits from a parent class, which itself is inherited from another class.
class Grandparent:
def show(self):
print("This is the Grandparent class")
class Parent(Grandparent):
pass
class Child(Parent):
pass
c = Child()
c.show() # Child inherits from Parent, which inherits from Grandparent
4. Hierarchical Inheritance (One Parent → Multiple Children)
One parent class is inherited by multiple child classes.
24
class Parent:
def show(self):
print("This is the Parent class")
class Child1(Parent):
pass
class Child2(Parent):
pass
c1 = Child1()
c2 = Child2()
c1.show() # Child1 inherits from Parent
c2.show() # Child2 inherits from Parent
5. Hybrid Inheritance (Combination of Two or More Types)
It is a mix of different types of inheritance.
class A:
def showA(self):
print("Class A")
class B(A):
def showB(self):
print("Class B")
class C(A):
def showC(self):
print("Class C")
class D(B, C):
pass
d = D()
d.showA() # Inherited from Class A
d.showB() # Inherited from Class B
25
d.showC() # Inherited from Class C
super() Method in Python:
The super() method is used in inheritance to call the parent class’s
constructor (__init__ method) or methods inside a child class. It helps reuse code
from the parent class instead of rewriting it.
class Parent:
def show(self):
print("This is Parent class")
class Child(Parent):
def show(self):
super().show() # Calls Parent's show method
print("This is Child class")
c = Child()
c.show()
Polymorphism in Python:
Polymorphism means one thing can have multiple forms. In Python, the same
function or method can work differently based on the object using it.
Example of Polymorphism
print(len("Python")) # Works for string
print(len([1, 2, 3])) # Works for list
Operator Overloading:
Operator overloading is a type of polymorphism where we define how operators
like +, -, >, etc., work for custom objects. It is done using special Dunder
(double underscore) methods.
class Box:
def __init__(self, weight):
self.weight = weight
26
def __add__(self, other): # Overloading `+`
return Box(self.weight + other.weight)
box1 = Box(5)
box2 = Box(10)
result = box1 + box2 # Calls __add__
print(result.weight) # Output: 15
Dunder Methods:
Dunder (Double Underscore) methods are built-in methods in Python that
start and end with __. They allow us to define how objects behave with operators
and functions.
Operator Dunder Method

+ (Addition) __add__(self, other)

- (Subtraction) __sub__(self, other)

* (Multiplication) __mul__(self, other)

> (Greater than) __gt__(self, other)

Delete an Object
Delete the object using del.
Class Car:
def __init__(self, brand):
self.brand = brand
my_car = Car("Toyota")
del my_car
print(my_car) # This will give an error
Private Attributes and Methods in Python
private attributes and methods are used to restrict access to certain variables
or functions within a class. This helps in data protection and encapsulation.

27
start with double underscores (__).
class Student:
def __init__(self, name, age):
self.name = name # Public attribute
self.__age = age # Private attribute
def __show_age(self): # Private method
print(f"Age: {self.__age}")
def display(self): # Public method
self.__show_age() # Accessing private method inside class
s1 = Student("Noor", 20)
print(s1.name) # Allowed
print(s1.__age) # Error! Private attribute
s1.display() # Allowed (Access private method inside class)

28

You might also like