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

Python

The document is a comprehensive guide to Python programming, covering its introduction, features, applications, and installation. It includes sections on Python basics, operators, control flow statements, functions, data structures, file handling, exception handling, and object-oriented programming. The content is structured with clear explanations and examples, making it suitable for both beginners and experienced developers.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python

The document is a comprehensive guide to Python programming, covering its introduction, features, applications, and installation. It includes sections on Python basics, operators, control flow statements, functions, data structures, file handling, exception handling, and object-oriented programming. The content is structured with clear explanations and examples, making it suitable for both beginners and experienced developers.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

TABLE OF CONTENTS

1.INTRODUCTION TO PYTHON ........................................................................................... 1


1.1 Overview of Python ......................................................................................................... 1
1.2 Features of Python ........................................................................................................... 1
1.3 Applications of Python ..................................................................................................... 1
1.4 Installing Python and Setting Up the Environment ......................................................... 2
1.5 Python Syntax and Code Structure .................................................................................. 2
2.PYTHON BASICS ................................................................................................................. 3
2.1 Writing and Running Python Programs ........................................................................... 3
2.2 Variables and Data Types ................................................................................................. 3
2.3 Input and Output Operations ............................................................................................ 3
2.4 Type Conversion and Type Casting ................................................................................. 4
3.OPERATORS IN PYTHON ................................................................................................... 5
3.1 Arithmetic Operators ........................................................................................................ 5
3.2 Comparison Operators ..................................................................................................... 6
3.3 Logical Operators............................................................................................................. 6
3.4 Bitwise Operators............................................................................................................. 7
3.5 Assignment Operators ...................................................................................................... 8
3.6 Membership Operators..................................................................................................... 9
3.7 Identity Operators ............................................................................................................ 9
4.CONTROL FLOW STATEMENTS ..................................................................................... 10
4.1 Conditional Statements .................................................................................................. 10
4.2 Looping Statements ....................................................................................................... 11
4.3 Loop Control Statements ............................................................................................... 12
5.FUNCTIONS IN PYTHON .................................................................................................. 14
5.1 Positional Arguments ..................................................................................................... 14
5.2 Default Arguments ......................................................................................................... 14
5.3 Keyword Arguments ...................................................................................................... 15
5.4 Arbitrary Positional Arguments (args) ........................................................................... 15
5.5 Arbitrary Keyword Arguments (kwargs) ....................................................................... 15
6.DATA STRUCTURES IN PYTHON ................................................................................... 17
6.1 Lists ................................................................................................................................ 17
6.2 Tuples ............................................................................................................................. 17
6.3 Sets ................................................................................................................................. 18
6.4 Dictionaries .................................................................................................................... 18
6.5 Strings as a Data Structure ............................................................................................. 19
7.FILE HANDLING ................................................................................................................ 20
7.1 Opening and Closing Files ............................................................................................. 20
7.2 Reading from a File ....................................................................................................... 20
7.3 Writing to a File ............................................................................................................. 21
7.4 Appending to a File ........................................................................................................ 21
7.5 Working with File Modes .............................................................................................. 21
8.EXCEPTION HANDLING .................................................................................................. 23
8.1 Introduction to Exceptions ............................................................................................. 23
8.2 Handling Exceptions using try and except..................................................................... 24
8.3 Using Multiple except Blocks........................................................................................ 24
8.4 Using else with try-except ............................................................................................. 25
8.5 The finally Block ........................................................................................................... 25
8.6 Raising Exceptions with raise ........................................................................................ 26
8.7 Custom Exceptions ........................................................................................................ 26
9.OBJECT-ORIENTED PROGRAMMING ........................................................................... 28
9.1 Introduction to OOP ....................................................................................................... 28
9.2 Classes and Objects........................................................................................................ 28
9.3 Constructors and the __init__ Method........................................................................... 29
9.4 Instance and Class Variables .......................................................................................... 29
9.5 Encapsulation and Access Modifiers ............................................................................. 30
9.6 Inheritance...................................................................................................................... 30
9.7 Polymorphism ................................................................................................................ 31
LIST OF FIGURES
FIG 1.1: - PYTHON .................................................................................................................. 2
FIG 2.1: - EXAMPLE CODE .................................................................................................... 4
FIG 4.1: - CONTROL STATEMENTS .................................................................................... 13
FIG 5.1: - EXAMPLE FUNCTIONS ...................................................................................... 16
FIG 8.1: - EXCEPTIONS HANDLING .................................................................................. 27
1.INTRODUCTION TO PYTHON

1.1 Overview of Python


Python is a high-level, interpreted programming language known for its simplicity and
readability. It was created by Guido van Rossum in the late 1980s and officially released in
1991. Python emphasizes code readability with its clean and easy-to-learn syntax, making it an
excellent choice for beginners and experienced developers alike.

Python is widely used in various domains, including web development, data science, artificial
intelligence, automation, and more. Its extensive standard library and support for third-party
packages make it a powerful tool for solving complex problems efficiently. Due to its
versatility, Python is one of the most popular programming languages in the world today.

1.2 Features of Python


Python offers several features that make it a preferred programming language for developers.
It is an interpreted language, meaning code is executed line by line, allowing for quick
debugging and testing. It supports multiple programming paradigms, including procedural,
object-oriented, and functional programming, giving developers flexibility in designing
solutions.

Another significant feature of Python is its portability. Python programs can run on various
operating systems, such as Windows, macOS, and Linux, without modification. Additionally,
Python has automatic memory management, reducing the need for manual memory allocation
and deallocation, which simplifies coding and improves performance.

1.3 Applications of Python


Python is used in numerous fields due to its extensive libraries and frameworks. In web
development, frameworks like Django and Flask make it easy to build scalable web
applications. In data science, libraries like NumPy, Pandas, and Matplotlib help analyze and
visualize data efficiently. Python is also a dominant language in artificial intelligence and
machine learning, with TensorFlow and PyTorch being widely used in model development.

Automation is another area where Python excels. With simple scripts, tasks like file handling,
data extraction, and web scraping can be automated, saving time and effort. Python is also
commonly used in cybersecurity, network programming, embedded systems, and even game
development, showcasing its versatility in the software industry.

1
1.4 Installing Python and Setting Up the Environment
Before starting with Python programming, it is essential to install Python and set up a suitable
development environment. The official Python website (python.org) provides downloadable
versions for different operating systems. The installation process is straightforward, with
options to include pip, the package manager for Python.

For writing and running Python programs, various integrated development environments
(IDEs) are available, such as PyCharm, VS Code, and Jupyter Notebook. The default Python
IDLE (Integrated Development and Learning Environment) is also a simple option for
beginners. Setting up a proper development environment ensures a smooth coding experience
and enables better debugging and execution of Python scripts.

FIG 1.1: - Python

1.5 Python Syntax and Code Structure


Python's syntax is designed to be intuitive and easy to read. Unlike many programming
languages that use curly braces {} to define code blocks, Python relies on indentation. Proper
indentation is crucial in Python as it determines the structure of the code and helps maintain
readability.

Python scripts typically start with a print() statement or variable declarations. Statements are
written in a single line, and comments are added using the # symbol. Multi-line comments can
be written using triple quotes (''' or """). Python follows a dynamic typing approach, meaning
variables do not require explicit type declarations, making code development faster and more
flexible.

2
2.PYTHON BASICS
2.1 Writing and Running Python Programs
Python programs are written as scripts in .py files or executed interactively in the Python shell.
The simplest way to run Python code is through the command line by typing python or python3,
followed by the script name. Python’s interactive mode allows users to test small code snippets
quickly.

Python provides various ways to execute scripts, including IDEs like PyCharm and VS Code,
text editors like Notepad++, and Jupyter Notebooks for interactive computing. Regardless of
the environment, Python’s easy-to-use syntax makes it a preferred choice for beginners and
professionals alike.

2.2 Variables and Data Types


In Python, variables store values that can be used later in the program. Unlike statically typed
languages, Python does not require explicit variable type declaration. A variable is created by
assigning a value using the = operator.

Python supports several built-in data types, including:

Integers (int) – Whole numbers like 10, -5, 1000.

Floating-point numbers (float) – Decimal numbers like 3.14, -0.99, 2.5.

Strings (str) – Textual data enclosed in single or double quotes, such as "Hello, World!".

Booleans (bool) – Logical values True and False.

Complex Numbers (complex) – Numbers with real and imaginary parts, such as 2 + 3j.

Python also allows type conversion between these data types using functions like int(), float(),
and str(), making it flexible for various operations.

2.3 Input and Output Operations


Python provides simple ways to interact with users through input and output functions. The
print() function is used to display messages or results on the screen. It can print strings,
numbers, or variables with formatted output using f-strings or the format() method.

3
For user input, Python uses the input() function, which reads input as a string. If numerical
operations are needed, the input must be converted using int() or float(). Handling input/output
efficiently is crucial for building interactive Python programs.

FIG 2.1: - EXAMPLE CODE

2.4 Type Conversion and Type Casting


Python allows implicit and explicit type conversion. Implicit conversion occurs when Python
automatically converts one data type to another, such as converting an integer to a float during
arithmetic operations.

Explicit conversion, or type casting, is done using functions like int(), float(), str(), and bool().
This is useful when performing operations that require specific data types, such as
mathematical calculations or string manipulations. Understanding type conversion helps avoid
errors and ensures data consistency in programs.

4
3.OPERATORS IN PYTHON
Operators are symbols that perform operations on variables and values. Python supports
various types of operators to handle mathematical, logical, and bitwise operations.

3.1 Arithmetic Operators


Arithmetic operators are used for basic mathematical calculations like addition, subtraction,
multiplication, and division.

For example:

a = 10

b=3

print("Addition:", a + b)

print("Subtraction:", a - b)

print("Multiplication:", a * b)

print("Division:", a / b)

print("Floor Division:", a // b)

print("Modulus:", a % b)

print("Exponentiation:", a ** b)

When this program is executed, the output will be:

Addition: 13

Subtraction: 7

Multiplication: 30

Division: 3.3333

Floor Division: 3

Modulus: 1

Exponentiation: 1000

5
The // operator performs floor division, meaning it rounds down the result to the nearest whole
number. The ** operator raises the number to the power of another number.

3.2 Comparison Operators


Comparison operators compare two values and return True or False. These operators are used
in conditional statements.

For example:

x=5

y = 10

print("x is equal to y:", x == y)

print("x is not equal to y:", x != y)

print("x is greater than y:", x > y)

print("x is less than y:", x < y)

print("x is greater than or equal to y:", x >= y)

print("x is less than or equal to y:", x <= y)

The output will be:

x is equal to y: False

x is not equal to y: True

x is greater than y: False

x is less than y: True

x is greater than or equal to y: False

x is less than or equal to y: True

3.3 Logical Operators


Logical operators are used to combine multiple conditions and return True or False.

For example:

a = True

6
b = False

print("a and b:", a and b)

print("a or b:", a or b)

print("not a:", not a)

The output will be:

a and b: False

a or b: True

not a: False

and returns True only if both conditions are True.

or returns True if at least one condition is True.

not inverts the boolean value.

3.4 Bitwise Operators


Bitwise operators perform operations on the binary representation of numbers.

For example:

a = 5 (Binary: 0101)

b = 3 (Binary: 0011)

print("Bitwise AND:", a & b)

print("Bitwise OR:", a | b)

print("Bitwise XOR:", a ^ b)

print("Bitwise NOT of a:", ~a)

print("Left Shift:", a << 1)

print("Right Shift:", a >> 1)

The output will be:

Bitwise AND: 1

Bitwise OR: 7

7
Bitwise XOR: 6

Bitwise NOT of a: -6

Left Shift: 10

Right Shift: 2

Bitwise operations work as follows:

& (AND) sets bits that are 1 in both numbers.

| (OR) sets bits that are 1 in at least one number.

^ (XOR) sets bits that are 1 in only one number.

~ (NOT) inverts all bits.

<< (Left Shift) shifts bits left, multiplying by 2^n.

>> (Right Shift) shifts bits right, dividing by 2^n.

3.5 Assignment Operators


Assignment operators assign values to variables.

For example:

x = 10

x += 5 (Equivalent to x = x + 5)

x -= 3 (Equivalent to x = x - 3)

x *= 2 (Equivalent to x = x * 2)

x /= 4 (Equivalent to x = x / 4)

x %= 3 (Equivalent to x = x % 3)

x **= 2 (Equivalent to x = x ** 2)

If the initial value of x is 10, the output after each operation will be:

x = 15

x = 12

x = 24

8
x = 6.0

x = 0.0

x = 0.0

3.6 Membership Operators


Membership operators check if a value exists in a sequence like a list, tuple, or string.

For example:

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

print(3 in my_list)

print(10 not in my_list)

The output will be:

True

True

in checks if an element exists in the sequence.

not in checks if an element is not in the sequence.

3.7 Identity Operators


Identity operators check if two variables reference the same object in memory.

For example:

a = [10, 20, 30]

b=a

c = [10, 20, 30]

print(a is b)

print(a is not c)

The output will be:

True

True

9
4.CONTROL FLOW STATEMENTS
Control flow statements determine the sequence in which instructions are executed in a
program. Python provides conditional statements, loops, and loop control mechanisms to
control the flow of execution.

4.1 Conditional Statements


Conditional statements allow decision-making based on conditions. Python provides if, if-else,
and if-elif-else statements to execute different blocks of code based on conditions.

For example:

num = 10

if num > 0:

print("Positive number")

The output will be:

Positive number

In cases where there are two possibilities, an if-else statement is used:

num = -5

if num > 0:

print("Positive number")

else:

print("Negative number")

Output:

Negative number

For multiple conditions, if-elif-else is used:

num = 0

if num > 0:

print("Positive number")

10
elif num < 0:

print("Negative number")

else:

print("Zero")

Output:

Zero

4.2 Looping Statements


Loops are used to execute a block of code multiple times. Python provides while and for loops
for iteration.

A while loop runs as long as a condition remains True:

count = 1

while count <= 5:

print("Count:", count)

count += 1

Output:

Count: 1

Count: 2

Count: 3

Count: 4

Count: 5

A for loop is used to iterate over sequences like lists, tuples, and strings:

for i in range(1, 6):

print("Iteration:", i)

Output:

Iteration: 1

11
Iteration: 2

Iteration: 3

Iteration: 4

Iteration: 5

4.3 Loop Control Statements


Python provides control statements to alter the normal flow of loops.

The break statement terminates a loop:

for i in range(1, 10):

if i == 5:

break

print(i)

Output:

The continue statement skips the current iteration and moves to the next one:

for i in range(1, 6):

if i == 3:

continue

print(i)

Output:

12
5

The pass statement does nothing and is used as a placeholder:

for i in range(1, 6):

if i == 3:

pass

print(i)

Output:

FIG 4.1: - Control Statements

13
5.FUNCTIONS IN PYTHON
Functions in Python allow code reuse and modular programming. Python supports different
types of function arguments, including positional arguments, keyword arguments, default
arguments, arbitrary positional arguments (*args), and arbitrary keyword arguments
(**kwargs).

5.1 Positional Arguments


Positional arguments are the most common way to pass values to a function. The order of
arguments in the function call must match the function definition.

Example:

def greet(name, age):

print("Hello", name, "You are", age, "years old.")

greet("Alice", 25)

Output:

Hello Alice You are 25 years old.

If the number of arguments in the function call does not match the function definition, an error
occurs.

5.2 Default Arguments


Default arguments allow functions to have default values if no argument is provided during the
function call.

Example:

def greet(name, age=18):

print("Hello", name, "You are", age, "years old.")

greet("Bob")

greet("Charlie", 22)

Output:

Hello Bob You are 18 years old.

14
Hello Charlie You are 22 years old.

If an argument is provided, it overrides the default value.

5.3 Keyword Arguments


Keyword arguments allow arguments to be passed using parameter names, making the order
irrelevant.

Example:

def greet(name, age):

print("Hello", name, "You are", age, "years old.")

greet(age=30, name="David")

Output:

Hello David You are 30 years old.

Using keyword arguments improves readability and avoids confusion in argument order.

5.4 Arbitrary Positional Arguments (args)


The *args parameter allows a function to accept any number of positional arguments as a tuple.

Example:

def sum_numbers(*numbers):

total = sum(numbers)

print("Sum:", total)

sum_numbers(1, 2, 3, 4, 5)

Output:

Sum: 15

The function can take any number of arguments, and they are stored in a tuple.

5.5 Arbitrary Keyword Arguments (kwargs)


The **kwargs parameter allows a function to accept any number of keyword arguments as a
dictionary.

15
Example:

def person_info(**info):

for key, value in info.items():

print(key, ":", value)

person_info(name="Eve", age=28, city="New York")

Output:

name : Eve

age : 28

city : New York

This is useful when a function must accept a varying number of named parameters.

FIG 5.1: - Example Functions

16
6.DATA STRUCTURES IN PYTHON
Data structures help in organizing and managing data efficiently. Python provides several built-
in data structures that allow storing and manipulating data in various ways. The primary data
structures in Python include:
Lists
Tuples
Sets
Dictionaries
Strings as a Data Structure

6.1 Lists
A list is an ordered, mutable collection that allows duplicate elements. Lists are defined using
square brackets [ ].
Example:
fruits = ["apple", "banana", "cherry", "apple"]
print(fruits)
Output:
['apple', 'banana', 'cherry', 'apple']
Lists support indexing, slicing, and various methods like:
Adding elements:
fruits.append("mango")
Removing elements:
fruits.remove("banana")
Looping through a list:
for fruit in fruits:
print(fruit)
Lists are versatile and used frequently in Python programming.

6.2 Tuples
A tuple is an ordered, immutable collection that allows duplicate elements. Tuples are defined
using parentheses ( ).
Example:
numbers = (10, 20, 30, 40, 50)
print(numbers)

17
Output:
(10, 20, 30, 40, 50)
Tuples are useful when data should not be modified after creation.
Accessing tuple elements:
print(numbers[1]) # Outputs: 20
Tuples can be used as dictionary keys and are more memory-efficient than lists.

6.3 Sets
A set is an unordered collection of unique elements. Sets are defined using curly braces { }.
Example:
unique_numbers = {1, 2, 3, 4, 5, 1, 2}
print(unique_numbers)
Output:
{1, 2, 3, 4, 5}
Sets do not allow duplicate values and provide fast membership testing.
Adding elements:
unique_numbers.add(6)
Removing elements:
unique_numbers.remove(3)
Sets are useful for operations like union and intersection.

6.4 Dictionaries
A dictionary is an unordered collection of key-value pairs. Dictionaries are defined using curly
braces { } with keys and values separated by colons :.
Example:
student = {"name": "Alice", "age": 21, "course": "Python"}
print(student)
Output:
{'name': 'Alice', 'age': 21, 'course': 'Python'}
Accessing values:
print(student["name"]) # Outputs: Alice
Adding a new key-value pair:
student["grade"] = "A"

18
Dictionaries are widely used for structured data representation.

6.5 Strings as a Data Structure


A string is a sequence of characters stored within single or double quotes. Strings are
immutable, meaning they cannot be changed after creation.
Example:
text = "Hello, Python!"
print(text)
String operations:
print(text.upper()) # Outputs: HELLO, PYTHON!
print(text.lower()) # Outputs: hello, python!
Strings support indexing and slicing:
print(text[0:5]) # Outputs: Hello
Strings are essential in Python for handling textual data.

19
7.FILE HANDLING
File handling allows reading, writing, and manipulating files in Python. Python provides built-
in functions to work with files using the open() function. The key operations in file handling
include:

Opening and Closing Files

Reading from a File

Writing to a File

Appending to a File

Working with File Modes

7.1 Opening and Closing Files


To work with files, Python provides the open() function. It requires a filename and mode as
arguments.

Syntax:

file = open("filename.txt", "mode")

Example:

file = open("example.txt", "r") # Open file in read mode

file.close() # Close the file

The close() method is used to free up system resources after file operations.

7.2 Reading from a File


To read the contents of a file, we use the read() method.

Example:

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

content = file.read()

print(content)

file.close()

To read line by line, we use readline() or readlines():

20
Example:

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

for line in file:

print(line.strip())

file.close()

7.3 Writing to a File


To write data into a file, use the write() method in write mode "w". This will overwrite existing
content.

Example:

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

file.write("Hello, Python!")

file.close()

After executing this, "example.txt" will contain:

Hello, Python!

7.4 Appending to a File


To add content without overwriting existing data, use append mode "a".

Example:

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

file.write("\nThis is a new line.")

file.close()

Now, "example.txt" contains:

Hello, Python!

This is a new line.

7.5 Working with File Modes


Python provides different file modes:

21
"r" → Read mode (default)

"w" → Write mode (overwrites file)

"a" → Append mode (adds content at the end)

"r+" → Read and write mode

"w+" → Write and read mode (overwrites)

"a+" → Append and read mode

Example of "r+" mode:

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

file.write("New Content")

file.seek(0) # Move cursor to beginning

print(file.read())

file.close()

22
8.EXCEPTION HANDLING
Exception handling in Python allows programs to deal with unexpected errors and prevent
crashes. Python provides a robust mechanism to handle runtime errors using the try-except
block. The key concepts in exception handling include:

Introduction to Exceptions

Handling Exceptions using try and except

Using Multiple except Blocks

Using else with try-except

The finally Block

Raising Exceptions with raise

Custom Exceptions

8.1 Introduction to Exceptions


An exception is an error that occurs during program execution, disrupting the normal flow.
Common exceptions in Python include:

ZeroDivisionError → Division by zero

TypeError → Invalid data type operation

ValueError → Incorrect value

FileNotFoundError → File does not exist

Example of an exception:

a = 10

b=0

print(a / b) # This will raise ZeroDivisionError

Output:

ZeroDivisionError: division by zero

To handle such errors, we use try-except blocks.

23
8.2 Handling Exceptions using try and except
We use try to test code and except to handle errors.

Example:

try:

a = 10

b=0

print(a / b)

except ZeroDivisionError:

print("Cannot divide by zero!")

Output:

Cannot divide by zero!

If an exception occurs in the try block, control jumps to except, preventing a crash.

8.3 Using Multiple except Blocks


We can handle different exceptions separately using multiple except blocks.

Example:

try:

x = int(input("Enter a number: "))

y = int(input("Enter another number: "))

print(x / y)

except ZeroDivisionError:

print("You cannot divide by zero.")

except ValueError:

print("Invalid input! Please enter a number.")

If the user enters "abc", a ValueError occurs, and the respective message is displayed.

24
8.4 Using else with try-except
The else block executes only if no exception occurs in try.

Example:

try:

num = int(input("Enter a number: "))

print("Square:", num * num)

except ValueError:

print("Please enter a valid number.")

else:

print("Operation successful!")

If input is valid, else executes, confirming successful execution.

8.5 The finally Block


The finally block executes regardless of whether an exception occurs. It is used for cleanup
operations like closing files or releasing resources.

Example:

try:

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

content = file.read()

print(content)

except FileNotFoundError:

print("File not found!")

finally:

print("Closing the program.")

Even if FileNotFoundError occurs, "Closing the program." is printed.

25
8.6 Raising Exceptions with raise
The raise keyword allows us to generate custom exceptions.

Example:

def check_age(age):

if age < 18:

raise ValueError("Age must be 18 or above.")

print("Access granted.")

try:

check_age(16)

except ValueError as e:

print("Error:", e)

Output:

Error: Age must be 18 or above.

This helps enforce rules and validations in programs.

8.7 Custom Exceptions


Python allows creating user-defined exceptions by inheriting from the Exception class.

Example:

class NegativeNumberError(Exception):

pass

def check_positive(num):

if num < 0:

raise NegativeNumberError("Negative number not allowed!")

print("Number is positive.")

try:

check_positive(-5)

26
except NegativeNumberError as e:

print("Error:", e)

Output:

Error: Negative number not allowed!

Custom exceptions improve error readability and debugging.

FIG 8.1: - Exceptions Handling

27
9.OBJECT-ORIENTED PROGRAMMING
Object-Oriented Programming (OOP) is a programming paradigm that organizes code into
objects, which combine data and behavior. Python supports OOP principles such as
encapsulation, inheritance, and polymorphism.
The key concepts in OOP include:
Introduction to OOP
Classes and Objects
Constructors and the init Method
Instance and Class Variables
Encapsulation and Access Modifiers
Inheritance
Polymorphism

9.1 Introduction to OOP


OOP is based on real-world objects and follows four main principles:
Encapsulation → Binding data and methods together
Abstraction → Hiding implementation details
Inheritance → Creating new classes from existing ones
Polymorphism → Using a single interface for different types
Python allows creating classes and objects, making programs more modular and reusable.

9.2 Classes and Objects


A class is a blueprint for creating objects, and an object is an instance of a class.
Example:
class Car:
def start(self):
print("Car is starting...")

my_car = Car() # Creating an object


my_car.start() # Calling method
Output:
Car is starting...

28
Here, Car is a class, and my_car is an object of that class.

9.3 Constructors and the __init__ Method


A constructor (__init__) initializes an object’s attributes when an object is created.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def display(self):
print(f"Name: {self.name}, Age: {self.age}")
p1 = Person("Alice", 25)
p1.display()
Output:
Name: Alice, Age: 25
The __init__ method automatically executes when an object is created.

9.4 Instance and Class Variables


Instance variables → Defined inside the constructor and unique for each object.
Class variables → Shared by all objects of a class.
Example:
class Student:
school = "ABC School" # Class variable

def __init__(self, name):


self.name = name # Instance variable

s1 = Student("John")
s2 = Student("Emma")
print(s1.name, s1.school)
print(s2.name, s2.school)
Output:
29
John ABC School
Emma ABC School

9.5 Encapsulation and Access Modifiers


Encapsulation restricts direct access to data, allowing controlled access via methods.
Access Modifiers in Python:
Public (name) → Accessible anywhere
Private (__name) → Cannot be accessed outside the class
Protected (_name) → Should not be modified outside the class
Example:
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private variable

def deposit(self, amount):


self.__balance += amount

def get_balance(self):
return self.__balance

acc = BankAccount(1000)
acc.deposit(500)
print(acc.get_balance()) # Outputs: 1500
Here, __balance cannot be accessed directly, ensuring data security.

9.6 Inheritance
Inheritance allows a class to acquire properties of another class.
Single Inheritance → One class inherits from another
Multiple Inheritance → A class inherits from multiple classes
Multilevel Inheritance → Inheritance in multiple levels
Example of Single Inheritance:
class Animal:
def make_sound(self):
30
print("Animal makes a sound")
class Dog(Animal):
def bark(self):
print("Dog barks")
d = Dog()
d.make_sound()
d.bark()
Output:
Animal makes a sound
Dog barks
The Dog class inherits the make_sound method from Animal.

9.7 Polymorphism
Polymorphism allows using a single function name for different types.
Example of method overriding:
class Shape:
def area(self):
print("Calculating area...")
class Circle(Shape):
def area(self):
print("Area of Circle = π × r²")
c = Circle()
c.area()
Output:
Area of Circle = π × r²
Here, the area method is overridden in the Circle class.

31

You might also like