0% found this document useful (0 votes)
20 views34 pages

Python Lab Manual

Python, created by Guido van Rossum in 1989, is a versatile programming language known for its simple syntax and readability, making it accessible for beginners and professionals. Officially released in 1991, Python supports multiple programming paradigms and has a vast standard library, contributing to its popularity across various fields. Key features include dynamic typing, cross-platform compatibility, and extensive community support, making it a preferred choice for web development, data science, and more.

Uploaded by

rupankarbapari13
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)
20 views34 pages

Python Lab Manual

Python, created by Guido van Rossum in 1989, is a versatile programming language known for its simple syntax and readability, making it accessible for beginners and professionals. Officially released in 1991, Python supports multiple programming paradigms and has a vast standard library, contributing to its popularity across various fields. Key features include dynamic typing, cross-platform compatibility, and extensive community support, making it a preferred choice for web development, data science, and more.

Uploaded by

rupankarbapari13
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

History of Python

Python was created by Guido van Rossum, a Dutch programmer, in December 1989 while he
was working at Centrum Wiskunde & Informatica (CWI) in the Netherlands. He started the
project as a hobby during his Christmas holidays, aiming to develop a new scripting language
that would fix some issues he had encountered in the ABC programming language, which he had
previously worked on.

Python’s design philosophy emphasized:

• Simple and readable syntax,


• Making programming easier and more accessible,
• Powerful features for both beginners and professionals.

The language was officially released to the public in 1991. Unlike many programming languages
developed by large teams or corporations, Python was initially developed single-handedly by van
Rossum. The name “Python” was inspired not by the snake, but by the British comedy group
“Monty Python’s Flying Circus”.

Python has evolved continuously, with a growing community and support from the Python
Software Foundation since 2001. Today, it is one of the most popular programming languages in
the world, used in web development, data science, AI, education, and many other fields.

Key Features of Python


1. Easy to Learn and Read
Python’s syntax is simple and clean, similar to English, making it easy for beginners to
read and write code quickly.
2. Interpreted Language
Python executes code line by line, which simplifies debugging and testing without the
need for prior compilation.
3. Dynamically Typed
Variable types are determined at runtime, so you don’t need to declare types explicitly,
allowing more flexibility when coding.
4. High-Level Language
Python abstracts complex details like memory management, letting you focus on solving
problems rather than technical specifics.
5. Object-Oriented Programming (OOP) Support
Python supports classes and objects, enabling code reuse, modularity, encapsulation, and
inheritance.
6. Multiple Programming Paradigms
You can write procedural, object-oriented, and functional code in Python, giving you
versatile approaches to problem-solving.
7. Extensive Standard Library
Python comes with a huge collection of ready-to-use modules and libraries for tasks such
as file I/O, math, internet protocols, and more.
8. Cross-Platform Compatibility
Python code runs on almost all operating systems (Windows, macOS, Linux) without
modification.
9. Free and Open Source
Python is completely free to use and share, supported by a strong community and Python
Software Foundation.
10. GUI Programming Support
Python supports building graphical user interfaces using libraries like Tkinter, PyQt, and
Kivy.
11. Integration Capabilities
Python can easily integrate with other languages like C, C++, and Java, and work well
with data formats like JSON and XML.

These features combine to make Python one of the most popular and versatile programming
languages today, suitable for beginners and professionals alike.

Basic Syntax of Python


1. Indentation
• Python uses indentation (spaces or tabs) to define code blocks instead of braces {} like
other languages.
• Indentation is mandatory for the code to run correctly.

Example:

python
if 5 > 2:
print("Five is greater than two!")

If indentation is missing, Python raises an error.

2. Comments
• Comments start with # and are ignored by Python.
• Use comments to explain your code.

Example:

python
# This is a comment
print("Hello, World!") # This prints to the screen
3. Variables and Assignment
• Variables are created when you assign a value.
• No need to declare the type explicitly.

Example:

python
x=5
name = "Alice"

4. Printing to the Console


• Use print() to display output.

Example:

python
print("Hello, World!")
print(x)

5. Data Types
• Python automatically assigns data types: int, float, string, boolean, list, tuple, dict, set.

Example:

python
a = 10 # int
b = 3.14 # float
c = "Python" # string
d = True # boolean

6. Basic Control Flow Syntax


• If statement syntax:

python
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is 10")
else:
print("x is less than 10")
• Loop syntax (for loop example):

python
for i in range(5):
print(i)

7. Functions
• Defined using def keyword with indentation for the function body.

Example:

python
def greet(name):
print("Hello, " + name + "!")

greet("Alice")

Variables in Python
What is a Variable?
• A variable is like a container that stores data.
• In Python, you create a variable simply by assigning a value to it using =.
• Python automatically detects the data type (integer, string, float, etc.).
• Variable names must start with a letter or underscore and are case-sensitive.

Example 1: Creating and Printing Variables


python
# Assign values to variables
name = "Dharmender"
age = 30
height = 5.9
is_student = False

# Print the variables


print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is Student:", is_student)
Explanation:
Variables store data of different types (string, int, float, boolean). You assign values directly, no
prior declaration needed.

Example 2: Changing Variable Type


python
x=4 # x is an integer
print(x, type(x))

x = "Sally" # Now x is a string


print(x, type(x))

Explanation:
Python variables can change type anytime by assigning a new value of a different type.

Example 3: Multiple Variable Assignment


python
a, b, c = 10, 20, 30
print(a, b, c)

x = y = z = 100
print(x, y, z)

Explanation:
You can assign multiple variables in one line or assign the same value to multiple variables
simultaneously.

Example 4: Checking Variable Type


python
num = 25
name = "Alice"
price = 19.99

print(type(num)) # int
print(type(name)) # str
print(type(price)) # float

Explanation:
Use the type() function to find out the data type of any variable.
Operators in Python
1. Arithmetic Operators
Used for basic mathematical calculations.

Operator Meaning Example Output

+ Addition 5+3 8

- Subtraction 10 - 4 6

* Multiplication 2*6 12

/ Division 9/3 3.0

% Modulo (remainder) 10 % 3 1

** Exponent (power) 4 ** 2 16

// Floor Division 10 // 3 3

Example:

python
a = 21
b = 10

print("a + b =", a + b) # Addition


print("a - b =", a - b) # Subtraction
print("a * b =", a * b) # Multiplication
print("a / b =", a / b) # Division
print("a % b =", a % b) # Modulo
print("a ** b =", a ** b) # Exponentiation
print("a // b =", a // b) # Floor Division
2. Assignment Operators
Used to assign or update values.

Operator Example Equivalent to

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

Example:

python
x = 10
x += 5 # Same as x = x + 5
print(x)
x *= 2 # Same as x = x * 2
print(x)

3. Comparison Operators
Compare two values and return Boolean results.

Operator Meaning Example

== Equal to x == y

!= Not equal to x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal x >= y

<= Less than or equal x <= y


Example:

python
a = 10
b = 20
print(a == b) # False
print(a != b) # True
print(a < b) # True
print(a >= 10) # True

4. Logical Operators
Used to combine conditional statements.

Operator Meaning Example

and True if both True x > 5 and y < 10

or True if either True x > 5 or y > 20

not Negation (True if False) not(x > 5)

Example:

python
x = 10
y=5
print(x > 5 and y < 10) # True
print(x > 20 or y < 10) # True
print(not(x > 5)) # False

5. Identity Operators
Test if two variables refer to the same object.

Operator Meaning Example

is True if same object x is y

is not True if different x is not y


Example:

python
x1 = [1, 2, 3]
y1 = x1
z1 = [1, 2, 3]

print(x1 is y1) # True (same object)


print(x1 is z1) # False (equal but different objects)

6. Membership Operators
Test if a value is in a sequence.

Operator Meaning Example

in True if value found 'a' in 'cat'

not in True if value absent 'z' not in 'cat'

Example:

python
fruit = "apple"
print('a' in fruit) # True
print('b' not in fruit) # True
1. Conditional Statements
a) If Statement
Concept:
Execute a block of code only if a specified condition is true.

Real-life example:
If it is raining, then take an umbrella.

Python code:
is_raining = True

if is_raining:
print("Take an umbrella!")

Output:

Take an umbrella!

b) If-Else Statement
Concept:
Choose between two blocks of code: one if the condition is true, else the other.

Real-life example:
If you pass the exam, celebrate; else, study harder.

Python code:

marks = 65

if marks >= 50:


print("You passed the exam!")
else:
print("Better luck next time, study harder!")

Output:

You passed the exam!


c) Nested If-Else
Concept:
An if or else block inside another if or else, allowing multiple decisions.

Real-life example:
If it’s a weekday, check if it’s a Monday. If Monday, go for gym; else, work. If weekend, relax.

Python code:

day = "Monday"

if day in ["Saturday", "Sunday"]:


print("Relax, it's the weekend!")
else:
if day == "Monday":
print("Go to the gym!")
else:
print("Go to work.")

Output:

Go to the gym!

2. Looping
a) For Loop
Concept:
Repeat a block of code a fixed number of times or over items in a sequence.

Real-life example:
Count the number of books on a shelf.

Python code:

books = ['Math', 'Physics', 'Chemistry']

for book in books:


print(f"Reading {book}")

Output:

Reading Math
Reading Physics
Reading Chemistry
b) While Loop
Concept:
Repeat a block of code as long as a condition remains true.

Real-life example:
Keep filling a bucket until it is full.

Python code:

water_level = 0

while water_level < 5:


print(f"Water level at {water_level} liters")
water_level += 1

Output:

Water level at 0 liters


Water level at 1 liters
Water level at 2 liters
Water level at 3 liters
Water level at 4 liters

c) Nested Loops
Concept:
A loop inside another loop, useful for multidimensional tasks.

Real-life example:
Printing a calendar: outer loop for months, inner loop for days.

Python code:

for week in range(1, 3): # weeks


for day in range(1, 6): # days in a week
print(f"Week {week}, Day {day}")

Output:

Week 1, Day 1
Week 1, Day 2
Week 1, Day 3
Week 1, Day 4
Week 1, Day 5
Week 2, Day 1
Week 2, Day 2
Week 2, Day 3
Week 2, Day 4
Week 2, Day 5
Control Statements
1. Break
Main Concept:
break is used to exit a loop immediately when a specific condition is met.

Real-life Example:
Leaving a queue as soon as you find your friend ahead.

Python Code:

for name in ["Alice", "Bob", "Charlie"]:


if name == "Bob":
print("Found Bob, breaking out of the loop!")
break
print("Checking", name)

Sample Output:

Checking Alice
Found Bob, breaking out of the loop!

2. Continue
Main Concept:
continue skips only the current iteration and moves to the next.

Real-life Example:
Skipping damaged apples when packing a basket, but continuing to check the rest.

Python Code:

for apple in ["good", "bad", "good"]:


if apple == "bad":
continue
print("Packing apple")

Sample Output:

Packing apple
Packing apple
3. Pass
Main Concept:
pass does nothing and acts as a placeholder when a statement is required syntactically.

Real-life Example:
Making a shopping list but leaving some items blank to fill later.

Python Code:

for i in range(3):
if i == 1:
pass
else:
print("Processing", i)

Sample Output:

Processing 0
Processing 2
String Manipulation
1. Accessing Strings
Main Concept:
Individual elements in a string can be accessed using indexes.

Real-life Example:
Reading specific letters in a name tag.

Python Code:

s = "Python"
print(s[0])
print(s[-1])

Sample Output:

P
n

2. Basic Operations
Concepts:
Concatenation (+), repetition (*), length (len()), and searching (in).

Real-life Example:
Combining first and last names, checking if ‘@’ is in an email.

Python Code:

first = "John"
last = "Doe"
print(first + " " + last) # Concatenation
print(first * 3) # Repetition
print(len(last)) # Length
print("@" in "john@[Link]") # Searching

Sample Output:

John Doe
JohnJohnJohn
3
True
3. String Slices
Main Concept:
Extracting parts of a string by specifying start and end indexes.

Real-life Example:
Cutting a slice out of a loaf of bread.

Python Code:

text = "Hello, World!"


print(text[0:5])
print(text[7:])
print(text[-6:-1])

Sample Output:

Hello
World!
World

4. String Functions and Methods


Main Concept:
Built-in tools for modifying and analyzing strings.

Real-life Example:
Auto-capitalizing names, counting occurrences of letters, searching for substrings.

Python Code:

msg = "welcome to python"


print([Link]())
print([Link]())
print([Link]("o"))
print([Link]("python"))
print([Link]("python", "coding"))

Sample Output:

Welcome to python
WELCOME TO PYTHON
2
11
welcome to coding
Lists in Python
1. Introduction to Lists
Concept:
A list is a collection of items in a particular order. Lists can hold different types of data (integers,
strings, etc.) and are mutable (can be changed after creation).

Real-life example:
A shopping list containing items you want to buy.

Python Code:

shopping_list = ["milk", "bread", "eggs", "fruits"]


print(shopping_list)

Output:

['milk', 'bread', 'eggs', 'fruits']

2. Accessing List Elements


Concept:
Access elements by index, starting at 0. Negative indexes access elements from the end.

Real-life example:
Getting the first or last item from your shopping list.

Python Code:

print("First item:", shopping_list[0])


print("Last item:", shopping_list[-1])

Output:

First item: milk


Last item: fruits
3. Operations on Lists
• Concatenation: Combine two lists using +.
• Repetition: Repeat a list using *.
• Membership: Check if an item is in the list using in.
• Length: Use len() to get number of items.

Code:

fruits = ["apple", "banana"]


vegetables = ["carrot", "lettuce"]

print(fruits + vegetables) # Concatenation


print(fruits * 2) # Repetition
print("apple" in fruits) # Membership
print(len(fruits)) # Length

Output:

['apple', 'banana', 'carrot', 'lettuce']


['apple', 'banana', 'apple', 'banana']
True
2

4. Working with Lists


Concept:
Lists are mutable; you can modify, add, or remove elements.

• Modify: list[index] = new_value


• Append: [Link](value)
• Insert: [Link](index, value)
• Remove: [Link](value)
• Pop: [Link](index)

Code:

shopping_list[1] = "whole grain bread" # Modify


shopping_list.append("butter") # Append
shopping_list.insert(2, "cheese") # Insert
shopping_list.remove("milk") # Remove
item = shopping_list.pop() # Pop last item
print(shopping_list)
print("Popped item:", item)

Output:

['whole grain bread', 'cheese', 'eggs', 'fruits']


Popped item: butter

5. List Functions and Methods


• Functions:
o len(list) — Length
o min(list), max(list) — Minimum or maximum (if list has comparable items)
• Methods:
o [Link]() — Sort in-place
o [Link]() — Reverse in-place
o [Link](value) — Find index of value
o [Link](value) — Count occurrences of value
o [Link]() — Remove all items

Code:

numbers = [3, 1, 4, 1, 5, 9, 2]

print("Length:", len(numbers))
print("Min:", min(numbers))
print("Max:", max(numbers))

[Link]()
print("Sorted:", numbers)

[Link]()
print("Reversed:", numbers)

print("Index of 5:", [Link](5))


print("Count of 1:", [Link](1))
[Link]()
print("Cleared list:", numbers)

Output:

Length: 7
Min: 1
Max: 9
Sorted: [1, 1, 2, 3, 4, 5, 9]
Reversed: [9, 5, 4, 3, 2, 1, 1]
Index of 5: 1
Count of 1: 2
Cleared list: []
Tuples in Python
1. Introduction
• Concept: A tuple is an ordered, immutable collection of elements.
• Real-life Example: Think of your birthdate (year, month, day) as a tuple. You can't
change your birthdate after it's set.
• Code Example:

birthdate = (1995, 12, 25)


print(birthdate)

2. Accessing Tuples
• Concept: Elements in a tuple are accessed by their index positions, just like lists
(indexing starts at 0).
• Real-life Example: In a (name, age, city) tuple, name is at index 0.
• Code Example:

person = ("Alice", 28, "Kolkata")


print(person[0])
print(person[-1])

3. Operations on Tuples
• Concatenation: Join two tuples using +.
• Repetition: Repeat a tuple with *.
• Slicing: Extract a range of elements like lists.
• Code Example:

t1 = (1, 2, 3)
t2 = (4, 5)
print(t1 + t2)
print(t2 * 2)
print(t1[1:3])

4. Working with Tuples


• Immutability: Tuples cannot be changed after creation (no append, remove, etc.).
• Packing/Unpacking: Assign multiple values at once or extract values.
• Code Example:

python
scores = (95, 89, 90)
s1, s2, s3 = scores
print(s2)
5. Functions and Methods
• Functions: Used like lists: len(), min(), max(), sum().
• Methods: Only count() and index() are tuple-specific.
• Code Example:

python
t = (2, 3, 2, 5, 3)
print(len(t))
print([Link](2))
print([Link](5))
print(min(t), max(t))
Dictionaries in Python
1. Introduction
• Concept: Dictionaries are collections of data in key-value pairs.
• Real-life Example: A contact book mapping names to phone numbers.
• Code Example:

contact = {"Alice": "9876543210", "Bob": "9123456780"}


print(contact)
# Output: {'Alice': '9876543210', 'Bob': '9123456780'}

2. Accessing Values
• Access by Key: Use dict[key] or [Link](key).
• Example:

print(contact["Bob"]) # Output: 9123456780


print([Link]("Eve")) # Output: None

3. Working with Dictionaries


• Add/Update: dict[key] = value
• Delete: del dict[key], or [Link](key)
• Traverse: Use .items(), .keys(), .values()
• Example:

contact["Eve"] = "9090909090" # Add


del contact["Alice"] # Delete
print(contact)
for name, phone in [Link]():
print(name, phone)

4. Properties
• Keys must be unique and immutable (string, number, tuple, etc.).
• Values can be of any type.
• Dictionaries are unordered.
• Example:

info = {(1, 2): "tuple as key"} # Valid

# Not allowed: {[1,2]: "list as key"} # Error!


Functions in Python
1. Defining a Function
• Use def keyword.
• Example:

def greet(name):
print("Hello,", name)

2. Calling a Function
• Example:

greet("Maya") # Output: Hello, Maya

3. Types of Functions
• User-defined: Made using def.
• Built-in: len(), print(), etc.

4. Function Arguments
• Positional: Order matters.
• Keyword: Explicitly specify (name="abc").
• Default: Argument with default value (def f(a=10))
• Variable Length: *args (tuple), **kwargs (dict).
• Example:

def demo(*args, **kwargs):


print("Positional:", args)
print("Keyword:", kwargs)

demo(1, 2, 3, name="Bob", subject="Python")


# Output:
# Positional: (1, 2, 3)
# Keyword: {'name': 'Bob', 'subject': 'Python'}
5. Anonymous Functions (Lambda)
• Single expression, no def/name needed.
• Example:

square = lambda x: x*x


print(square(4)) # Output: 16

6. Global and Local Variables


• Local: Defined inside function, accessible only there.
• Global: Defined outside, accessible everywhere.
• Example:

x = 10 # Global
def show():
x=5 # Local
print(x)
show() # Output: 5
print(x) # Output: 10
1. Modules and Importing
What is a Module?
A module is a Python file (.py) containing reusable code - functions, classes, and variables.
Modules promote code reusability, maintainability, and modularity.

Real-life analogy: A library book containing pre-written solutions you can borrow instead of
rewriting everything.

Import Syntax Variations:


# 1. Import entire module
import math
print([Link](16)) # 4.0

# 2. Import specific function


from math import sqrt, pi
print(sqrt(25), pi) # 5.0 3.14159...

# 3. Import with alias


import math as m
print([Link]) # 3.14159...

# 4. Import everything (use sparingly!)


from math import *
print(cos(0)) # 1.0

2. Math Module -
Key Constants & Functions:
import math

# Constants
print([Link]) # 3.141592653589793
print(math.e) # 2.718281828459045
print([Link]) # 6.283185307179586 (2π)

# Power functions
print([Link](2, 3)) # 8.0
print([Link](16)) # 4.0
print(2 ** 0.5) # Same as sqrt(2)

# Trigonometric
print([Link]([Link]/2)) # 1.0
print([Link](1.57)) # ~90 degrees
# Rounding
print([Link](4.7)) # 4
print([Link](4.7)) # 5

# Logarithmic
print([Link](100, 10)) # 2.0 (log base 10)
print(math.log2(8)) # 3.0

Example :

import math

def circle_properties(radius):
area = [Link] * [Link](radius, 2)
circumference = 2 * [Link] * radius
return area, circumference

r = float(input("Enter radius: "))


area, circ = circle_properties(r)
print(f"Area: {area:.2f}, Circumference: {circ:.2f}")

3. Random Module -
Key Functions:
import random

# Basic random numbers


print([Link]()) # Float [0.0, 1.0)
print([Link](1, 10)) # Integer [1, 10]
print([Link](1.5, 5.5)) # Float range

# Sequence operations
colors = ['red', 'green', 'blue']
print([Link](colors)) # Pick one
print([Link](colors, 2)) # Pick 2 unique
[Link](colors) # Shuffle in-place
print(colors)

# Distributions
print([Link](100, 15)) # Normal distribution (mean=100, std=15)
4. Packages & Composition
Module vs Package:
project/

├── [Link] # Single file = Module

└── mypackage/ # Folder = Package
├── __init__.py # Makes it a package (can be empty)
├── [Link]
└── [Link]

Package Structure Example:


math_operations/
├── __init__.py
├── [Link] # add(), subtract()
└── [Link] # factorial(), power()

[Link]:

def add(a, b):


return a + b

def subtract(a, b):


return a - b

Importing from package:

from math_operations.basic import add, subtract


from math_operations import advanced

print(add(5, 3)) #8
print([Link](5)) # 120
5. Input/Output Operations
Screen Output - Advanced Formatting:
name = "Alice"
score = 95.678
# f-strings
print(f"{name} scored {score:.1f}%")

# format() method
print("Score: {:.2f}".format(score))

# % formatting (legacy)
print("Score: %.1f" % score)

Keyboard Input -
def get_positive_number(prompt):
while True:
try:
num = float(input(prompt))
if num > 0:
return num
print("Please enter a positive number!")
except ValueError:
print("Invalid input! Enter a number.")

radius = get_positive_number("Enter radius: ")

6. File Handling
File Modes:
'r' - Read (default)
'w' - Write (overwrite)
'a' - Append
'r+' - Read+Write
'b' - Binary mode (add to any mode)

Complete File Operations:


# 1. Writing structured data
students = [("101", "Alice", 95), ("102", "Bob", 87)]

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


[Link]("Roll,Name,Marks\n")
for roll, name, marks in students:
[Link](f"{roll},{name},{marks}\n")
# 2. Reading and processing
def analyze_grades(filename):
total = 0
count = 0

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


next(f) # Skip header
for line in f:
roll, name, marks = [Link]().split(",")
marks = float(marks)
total += marks
count += 1

return total / count if count > 0 else 0

avg = analyze_grades("[Link]")
print(f"Class average: {avg:.2f}")
1. What is an Exception?
Definition: An exception is an event that disrupts the normal flow of program execution due to
an error or unexpected condition.

Real-life Analogy: When you're driving and suddenly hit a roadblock, you need to take a detour.
Exceptions are like roadblocks in your code.

Common Built-in Exceptions:

ZeroDivisionError # 10 / 0
IndexError # list[10] when list has 5 elements
KeyError # dict['nonexistent']
ValueError # int("abc")
TypeError # "hello" + 5
FileNotFoundError # open("[Link]")

Example - Without Exception Handling:

python
print("Start")
result = 10 / 0 # CRASH! Program stops here
print("End") # Never executed

Output: ZeroDivisionError: division by zero

2. Exception Handling Mechanism


Syntax:

try:
# Risky code that might raise exception
risky_operation()
except ExceptionType1:
# Handle specific exception
except ExceptionType2 as e:
# Handle with exception details
except: # Generic catch-all (use carefully)
# Handle any other exception
else:
# Executes ONLY if no exception occurred
finally:
# ALWAYS executes (cleanup code)
3. Try-Except Clause (Core Mechanism)
Basic try-except:
try:
num = int(input("Enter a number: "))
result = 100 / num
print(f"Result: {result}")
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Please enter a valid number!")

Sample Output 1:

Enter a number: 0
Cannot divide by zero!

Sample Output 2:

Enter a number: abc


Please enter a valid number!

4. Try-Except-Else-Finally (Complete Structure)


def divide_safely(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Division by zero error!")
result = None
except TypeError:
print("Both arguments must be numbers!")
result = None
else:
print("Division successful!")
finally:
print("Operation completed (cleanup done)")
return result

print(divide_safely(10, 2)) # Works fine


print(divide_safely(10, 0)) # Handles error

Output:

Division successful!
Operation completed (cleanup done)
5.0
Division by zero error!
5. Multiple Exception Handling Patterns
Pattern 1: Multiple except blocks
python
try:
lst = [1, 2, 3]
idx = int(input("Enter index: "))
print(lst[idx])
except IndexError:
print("Index out of range!")
except ValueError:
print("Enter valid index!")
except Exception as e:
print(f"Unexpected error: {e}")

Pattern 2: Tuple of exceptions


python
try:
num = eval(input("Enter expression: "))
except (ZeroDivisionError, ValueError, SyntaxError) as e:
print(f"Math error: {e}")

6. User-Defined (Custom) Exceptions


Why? Handle application-specific errors that built-in exceptions can't cover.

class InsufficientFundsError(Exception):
"""Raised when withdrawal exceeds balance"""
def __init__(self, balance, amount):
[Link] = balance
[Link] = amount
[Link] = f"Insufficient funds! Balance: Rs{balance}, Need: Rs{amount}"
super().__init__([Link])

class BankAccount:
def __init__(self, balance=1000):
[Link] = balance

def withdraw(self, amount):


try:
if amount > [Link]:
raise InsufficientFundsError([Link], amount)
[Link] -= amount
print(f"Withdrawal successful. New balance: Rs{[Link]}")
except InsufficientFundsError as e:
print(f" {e}")
except TypeError:
print("Amount must be a number!")
# Demo
account = BankAccount(500)
[Link](300) # Success
[Link](300) # Custom exception

Output:

Withdrawal successful. New balance: Rs200


Insufficient funds! Balance: Rs200, Need: Rs300

Exception Triggered By Example


ZeroDivisionError / 0 10/0
IndexError Invalid list index lst[10]
KeyError Invalid dict key d['missing']
ValueError Wrong value type int('abc')
TypeError Wrong operand types 'a' + 1
FileNotFoundError Missing file open('[Link]')
ImportError Missing module import nonexistent

You might also like