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

Python

This document serves as a comprehensive guide to Python programming, covering topics from installation and basic syntax to advanced concepts like object-oriented programming and database connectivity. It includes sections on Python features, data structures, control flow statements, functions, and libraries such as NumPy and Pandas. The document is structured with a detailed table of contents, making it easy to navigate through various Python programming concepts and applications.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python

This document serves as a comprehensive guide to Python programming, covering topics from installation and basic syntax to advanced concepts like object-oriented programming and database connectivity. It includes sections on Python features, data structures, control flow statements, functions, and libraries such as NumPy and Pandas. The document is structured with a detailed table of contents, making it easy to navigate through various Python programming concepts and applications.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 47

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......................................................................................11

4.1 Conditional Statements..................................................................................................11

4.2 Looping Statements........................................................................................................12

4.3 Loop Control Statements................................................................................................13

5.FUNCTIONS IN PYTHON..................................................................................................15

5.1 Positional Arguments.....................................................................................................15

5.2 Default Arguments.........................................................................................................15


5.3 Keyword Arguments......................................................................................................16

5.4 Arbitrary Positional Arguments (args)...........................................................................16

5.5 Arbitrary Keyword Arguments (kwargs)........................................................................16

6.DATA STRUCTURES IN PYTHON....................................................................................18

6.1 Lists................................................................................................................................18

6.2 Tuples.............................................................................................................................19

6.3 Sets.................................................................................................................................19

6.4 Dictionaries....................................................................................................................20

6.5 Strings as a Data Structure.............................................................................................20

7.FILE HANDLING................................................................................................................22

7.1 Opening and Closing Files.............................................................................................22

7.2 Reading from a File........................................................................................................22

7.3 Writing to a File.............................................................................................................23

7.4 Appending to a File........................................................................................................23

7.5 Working with File Modes...............................................................................................24

8.EXCEPTION HANDLING..................................................................................................25

8.1 Introduction to Exceptions.............................................................................................25

8.2 Handling Exceptions using try and except.....................................................................26

8.3 Using Multiple except Blocks........................................................................................26

8.4 Using else with try-except..............................................................................................27

8.5 The finally Block............................................................................................................27

8.6 Raising Exceptions with raise........................................................................................28

8.7 Custom Exceptions.........................................................................................................28

9.OBJECT-ORIENTED PROGRAMMING............................................................................30

9.1 Introduction to OOP.......................................................................................................30

9.2 Classes and Objects........................................................................................................30

9.3 Constructors and the __init__ Method...........................................................................31


9.4 Instance and Class Variables..........................................................................................31

9.5 Encapsulation and Access Modifiers.............................................................................32

9.6 Inheritance......................................................................................................................33

9.7 Polymorphism................................................................................................................34

10. MODULES AND PACKAGES.........................................................................................35

10.1 Importing Modules and Using Built-in Modules.........................................................35

10.2 Creating and Importing User-defined Modules...........................................................35

10.3 Understanding Python Packages and Namespaces......................................................35

10.4 Installing and Managing External Packages with pip..................................................36

10.5 Exploring the Python Standard Library.......................................................................36

11. WORKING WITH NUMPY AND PANDAS....................................................................37

11.1 Introduction to NumPy and Its Advantages.................................................................37

11.2 Creating and Manipulating NumPy Arrays..................................................................37

11.3 Introduction to Pandas and Its Advantages..................................................................37

11.4 Working with Pandas DataFrames and Series..............................................................38

11.5 Data Cleaning and Processing with Pandas.................................................................38

12. DATABASE CONNECTIVITY IN PYTHON..................................................................39

12.1 Introduction to Databases and SQL.............................................................................39

12.2 Connecting Python with SQLite Database...................................................................39

12.3 Performing CRUD Operations using Python...............................................................39

12.4 Using MySQL with Python (MySQL Connector)........................................................40

12.5 Working with ORM (Object-Relational Mapping) using SQLAlchemy.....................40

13. MULTITHREADING AND CONCURRENCY...............................................................41

13.1 Introduction to Multithreading and Concurrency........................................................41

13.2 Working with the Threading Module...........................................................................41

13.3 Synchronization and Thread Safety.............................................................................41

13.4 Using Multiprocessing for True Parallelism................................................................42


13.5 Asynchronous Programming with Asyncio..................................................................42
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

1
commonly used in cybersecurity, network programming, embedded systems, and even game
development, showcasing its versatility in the software industry.

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

7
Bitwise OR: 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

8
x = 12

x = 24

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)

9
The output will be:

True

True

10
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:

11
print("Positive number")

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:

12
Iteration: 1

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:

13
2

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

14
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:

15
Hello Bob You are 18 years old.

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.

16
5.5 Arbitrary Keyword Arguments (kwargs)
The **kwargs parameter allows a function to accept any number of keyword arguments as a
dictionary.

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

17
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:

18
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)

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:

19
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"

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:

20
print(text[0:5]) # Outputs: Hello

Strings are essential in Python for handling textual data.

21
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)

22
file.close()

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

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.

23
7.5 Working with File Modes
Python provides different file modes:

"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()

24
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

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

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.")

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

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.

27
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:

28
check_positive(-5)

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

29
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):

30
print("Car is starting...")

my_car = Car() # Creating an object

my_car.start() # Calling method

Output:

Car is starting...

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.

31
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:

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:

32
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):

print("Animal makes a sound")

class Dog(Animal):

33
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.

34
10. MODULES AND PACKAGES

10.1 Importing Modules and Using Built-in Modules


Python provides a modular programming approach, where large codebases can be divided
into smaller, manageable files known as modules. A module in Python is simply a file
containing Python definitions and statements. These modules allow code reuse and
organization. Python comes with a rich collection of built-in modules, such as math, os, sys,
and datetime, which provide ready-to-use functionalities. The import statement is used to
load these modules into a program, allowing access to their functions and variables.

For example, the math module provides mathematical functions like sqrt(), pow(), and
factorial(). To use these functions, one can import the module using import math and call
math.sqrt(16), which returns 4.0. Additionally, Python allows importing specific functions
from a module using the from keyword, such as from math import sqrt, enabling direct use
without prefixing with the module name.

10.2 Creating and Importing User-defined Modules


In addition to built-in modules, Python allows developers to create their own modules. A
user-defined module is simply a .py file containing functions, classes, or variables that can be
reused across different programs. This helps in maintaining clean and efficient code. To
create a module, one writes a Python script and saves it with a .py extension. For example, a
file named mymodule.py containing a function def greet(): print("Hello, World!") can be
imported using import mymodule and accessed with mymodule.greet().

Python also allows aliasing modules using the as keyword. For instance, import mymodule as
mm lets the module be referenced using mm.greet(). Moreover, one can use from mymodule
import greet to directly call greet() without prefixing it with the module name. This flexibility
makes modular programming in Python highly efficient and scalable.

10.3 Understanding Python Packages and Namespaces


A package in Python is a collection of related modules organized into a directory structure.
Packages facilitate better organization of large applications. A package is identified by the
presence of an __init__.py file, which may be empty or contain initialization code. For
instance, a package named mypackage may contain multiple modules such as module1.py,

35
module2.py, etc. To use a module from a package, one can write import mypackage.module1
and access its functions as mypackage.module1.function_name().

Namespaces in Python help avoid naming conflicts by ensuring that variable and function
names are unique within different scopes. Python provides different types of namespaces,
including local, global, and built-in namespaces. The globals() and locals() functions can be
used to inspect global and local namespaces, respectively. Understanding packages and
namespaces allows developers to build scalable and organized Python applications.

10.4 Installing and Managing External Packages with pip


Python offers a package manager called pip (Python Package Installer) to install and manage
third-party packages. These packages are hosted on the Python Package Index (PyPI), a
repository containing thousands of open-source libraries for various applications, such as web
development, data science, and automation. To install a package, the command pip install
package_name is used, such as pip install numpy to install NumPy.

To check installed packages, the command pip list is used, which displays a list of all
installed packages along with their versions. Updating a package is done using pip install --
upgrade package_name, while removing a package is possible with pip uninstall
package_name. Additionally, developers can use requirements.txt to list dependencies and
install them in bulk using pip install -r requirements.txt, ensuring a smooth package
management workflow.

10.5 Exploring the Python Standard Library


The Python Standard Library is a collection of built-in modules that provide functionality for
various tasks without requiring external installations. These modules cover file handling,
networking, mathematics, regular expressions, and more. Some widely used standard library
modules include os (for interacting with the operating system), sys (for system-related
operations), json (for JSON processing), and re (for regular expressions).

For example, the os module allows file and directory management with functions like
os.listdir() to list files in a directory and os.remove() to delete a file. The json module helps in
parsing and generating JSON data with functions like json.dumps() and json.loads().
Leveraging the Python Standard Library enables efficient programming without relying on
additional dependencies.

36
11. WORKING WITH NUMPY AND PANDAS

11.1 Introduction to NumPy and Its Advantages


NumPy (Numerical Python) is a powerful library for numerical computing in Python. It
provides support for multi-dimensional arrays, mathematical operations, and efficient
handling of large datasets. Unlike Python lists, NumPy arrays (ndarrays) are more memory-
efficient and significantly faster for numerical computations. NumPy supports various
operations such as element-wise arithmetic, linear algebra, statistical computations, and
broadcasting.

One of the key advantages of NumPy is its ability to handle large datasets efficiently using
optimized C-based implementations. Functions like numpy.array() allow the creation of
arrays, while operations such as numpy.mean(), numpy.sum(), and numpy.dot() enable
efficient numerical computations. The performance of NumPy makes it a fundamental library
for data science, machine learning, and scientific computing.

11.2 Creating and Manipulating NumPy Arrays


NumPy arrays can be created using numpy.array() by passing a list or tuple. Arrays can have
one or multiple dimensions, known as 1D, 2D, or multi-dimensional arrays. For instance,
numpy.zeros() and numpy.ones() create arrays filled with zeros or ones, while
numpy.arange(start, stop, step) generates sequences of numbers.

Manipulating arrays includes reshaping using numpy.reshape(), concatenation with


numpy.concatenate(), and element-wise operations like addition, subtraction, multiplication,
and division. NumPy also supports indexing and slicing, allowing efficient data retrieval from
large datasets. Broadcasting in NumPy enables performing operations on arrays of different
shapes without explicit loops, optimizing performance.

11.3 Introduction to Pandas and Its Advantages


Pandas is a powerful data manipulation and analysis library built on top of NumPy. It
provides two main data structures: Series (one-dimensional labeled arrays) and DataFrames
(two-dimensional tables similar to Excel or SQL tables). Pandas is widely used for data
cleaning, transformation, and analysis due to its easy-to-use functions and seamless
integration with other Python libraries.

37
One of the key advantages of Pandas is its ability to handle missing data efficiently using
dropna() and fillna() functions. The read_csv() and read_excel() functions allow easy loading
of datasets, while operations like filtering, grouping, and merging help in data transformation.
The Pandas library is essential for working with structured datasets, making it indispensable
for data science applications.

11.4 Working with Pandas DataFrames and Series


A Series in Pandas is a one-dimensional labeled array that can store any data type. It is
created using pandas.Series(data, index). A DataFrame is a two-dimensional labeled structure
with rows and columns, created using pandas.DataFrame(data, columns). DataFrames can be
created from dictionaries, lists, or NumPy arrays.

Data manipulation in Pandas includes indexing, slicing, filtering, and applying functions
using apply(). DataFrames can be modified using functions like add(), drop(), and merge().
The groupby() function is used for aggregating data, while pivot_table() helps in reshaping
data. The ability to perform vectorized operations makes Pandas an efficient tool for handling
large datasets.

11.5 Data Cleaning and Processing with Pandas


Data cleaning is an essential step in data analysis, and Pandas provides various functions to
handle missing values, duplicate records, and inconsistent data. The dropna() function
removes missing values, while fillna(value) replaces them with a specified value. The
drop_duplicates() method removes duplicate records, ensuring data integrity.

Data transformation includes converting data types using astype(), renaming columns with
rename(), and changing index labels with set_index(). Pandas also supports handling
categorical data, applying functions to entire columns, and merging datasets using concat()
and merge(). These capabilities make Pandas a powerful tool for preprocessing real-world
data before performing analysis or machine learning tasks.

38
12. DATABASE CONNECTIVITY IN PYTHON

12.1 Introduction to Databases and SQL


A database is an organized collection of data that can be easily accessed, managed, and
updated. Structured Query Language (SQL) is the standard language for interacting with
relational databases such as MySQL, PostgreSQL, SQLite, and SQL Server. SQL allows
users to perform operations like inserting, updating, deleting, and retrieving data using
queries.

Python provides various libraries for database connectivity, including sqlite3 for SQLite,
mysql-connector-python for MySQL, and psycopg2 for PostgreSQL. These libraries allow
seamless interaction with databases, enabling developers to execute queries and manage data
efficiently. Using databases in Python applications ensures data persistence, integrity, and
structured storage.

12.2 Connecting Python with SQLite Database


SQLite is a lightweight, serverless, self-contained database engine that is built into Python.
The sqlite3 module in Python allows interaction with SQLite databases using SQL
commands. To connect to an SQLite database, the connect() function is used:

First, import the sqlite3 module and create a connection using


sqlite3.connect("mydatabase.db"). This will create a new SQLite database file if it does not
exist. After that, create a cursor object using conn.cursor(), which allows executing SQL
commands.

12.3 Performing CRUD Operations using Python


CRUD stands for Create, Read, Update, and Delete, which are the four fundamental database
operations. These can be performed using SQL queries in Python.

To insert data into a table, use the SQL command "INSERT INTO students (name, age)
VALUES ('Alice', 22)" and execute it with the cursor. To save the changes, call
conn.commit().

To retrieve data from a table, execute "SELECT * FROM students" and use cursor.fetchall()
to fetch all rows. Iterate through the result and print each row.

39
To update data, use "UPDATE students SET age = 23 WHERE name = 'Alice'" and execute
it. Similarly, to delete data, execute "DELETE FROM students WHERE name = 'Alice'".

CRUD operations allow efficient data manipulation within Python programs while ensuring
database integrity.

12.4 Using MySQL with Python (MySQL Connector)


To connect Python with MySQL, install the mysql-connector-python package using the
command pip install mysql-connector-python.

To establish a connection, use mysql.connector.connect() with parameters such as host, user,


password, and database. Then, create a cursor object and execute SQL queries just like in
SQLite.

MySQL supports structured data storage and allows efficient querying and indexing for large-
scale applications. Connection pooling and optimized queries improve performance in
MySQL-based Python applications.

12.5 Working with ORM (Object-Relational Mapping) using SQLAlchemy


SQLAlchemy is a popular Python library for database interaction using an ORM approach,
which maps Python classes to database tables, reducing the need for raw SQL queries. It can
be installed using the command pip install sqlalchemy.

To define a table using SQLAlchemy, import the necessary modules, define a class
representing the table, and specify the column names and data types. Then, use
create_engine() to establish a connection to the database and call
Base.metadata.create_all(engine) to create the table.

ORM simplifies database interaction by representing database records as Python objects,


improving maintainability and scalability in large applications.

40
13. MULTITHREADING AND CONCURRENCY

13.1 Introduction to Multithreading and Concurrency


Multithreading and concurrency are essential concepts in modern programming, allowing
multiple tasks to execute simultaneously for improved performance and efficiency. In Python,
multithreading enables running multiple threads (lightweight processes) within a single
program, while concurrency allows managing multiple tasks that appear to run in parallel.

Python provides the threading module for implementing multithreading and the
multiprocessing module for running multiple processes. However, due to Python’s Global
Interpreter Lock (GIL), true parallel execution using threads is limited. Therefore,
multithreading is best suited for I/O-bound tasks, while multiprocessing is ideal for CPU-
bound tasks.

13.2 Working with the Threading Module


The threading module allows the creation and management of multiple threads. A thread is a
sequence of instructions that can run independently from the main program.

To create a thread in Python, use the Thread class from the threading module. Define a
function that performs a specific task and pass it as a target to Thread(). Start the thread using
the start() method.

Threads in Python share memory, allowing efficient task execution but requiring
synchronization mechanisms like locks to prevent race conditions and ensure data
consistency.

13.3 Synchronization and Thread Safety


Thread synchronization ensures that multiple threads do not interfere with each other while
accessing shared resources. Python provides the Lock class to prevent race conditions.

A lock restricts multiple threads from modifying a shared resource simultaneously. Use the
acquire() method before accessing shared data and release() after completing the operation.
This prevents data inconsistency and unpredictable behavior in multithreaded applications.

41
Other synchronization techniques include semaphores, condition variables, and event objects,
which help coordinate thread execution based on specific conditions.

13.4 Using Multiprocessing for True Parallelism


The multiprocessing module in Python allows the execution of multiple processes, bypassing
the limitations of the Global Interpreter Lock (GIL). Each process runs independently with its
own memory space, enabling true parallel execution on multi-core processors.

To use multiprocessing, create a Process object and specify a function as the target. Start the
process using the start() method, and use join() to ensure all processes complete before the
main program exits.

Multiprocessing is ideal for CPU-intensive tasks such as mathematical computations, data


analysis, and image processing, as it takes full advantage of multiple CPU cores.

13.5 Asynchronous Programming with Asyncio


Python’s asyncio module enables asynchronous programming, allowing tasks to execute
without blocking each other. Unlike multithreading and multiprocessing, which involve
separate threads or processes, asyncio uses coroutines that run within a single thread but
switch efficiently between tasks.

The async and await keywords define and run asynchronous functions. These functions pause
execution while waiting for external operations (e.g., network requests) and resume once the
operation is complete. This improves efficiency in applications that handle multiple I/O-
bound operations simultaneously, such as web scraping, network communication, and
database queries.

Asynchronous programming is widely used in web frameworks like FastAPI and Tornado,
ensuring responsive and scalable applications.

42

You might also like