0% found this document useful (0 votes)
4 views10 pages

Python Notes Part3

This document provides comprehensive notes on exception handling in Python, covering topics such as the try-except block, handling specific exceptions, using else and finally blocks, and raising custom exceptions. It also introduces built-in modules like math, random, and datetime, detailing their functionalities and important functions. The notes include examples for practical understanding and usage of these concepts.

Uploaded by

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

Python Notes Part3

This document provides comprehensive notes on exception handling in Python, covering topics such as the try-except block, handling specific exceptions, using else and finally blocks, and raising custom exceptions. It also introduces built-in modules like math, random, and datetime, detailing their functionalities and important functions. The notes include examples for practical understanding and usage of these concepts.

Uploaded by

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

PYTHON TRAINING NOTES DREAM A DREAM

Exception Handling in Python

1 Introduction to Exception Handling

An exception is an error that occurs during the execution of a program. If an exception is not handled
properly, it can cause the program to crash.

Python provides exception handling mechanisms to deal with runtime errors without stopping the
program.

🔹 Common Causes of Exceptions

1. Dividing by zero (ZeroDivisionError)


2. Using an undefined variable (NameError)
3. Accessing an invalid index in a list (IndexError)
4. Opening a non-existent file (FileNotFoundError)
5. Invalid data type operations (TypeError)

2 The try-except Block

To handle exceptions, we use the try-except block:

try:
# Code that may cause an error
num = int(input("Enter a number: "))
print("You entered:", num)
except:
# Code that runs if an error occurs
print("Invalid input! Please enter a number.")

� Explanation

 The try block contains code that may cause an error.


 If an error occurs, the program jumps to the except block, avoiding a crash.

PREPARED BY HARISH YADAV Page 1


PYTHON TRAINING NOTES DREAM A DREAM

3 Handling Specific Exceptions

Instead of catching all errors, we can handle specific exceptions separately.

try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error! Division by zero is not allowed.")
except ValueError:
print("Error! Please enter valid numbers.")
except:
print("An unexpected error occurred.")

� Explanation

 If the user divides by zero, ZeroDivisionError occurs.


 If the user enters a non-numeric value, ValueError occurs.
 Any other unknown error is handled by the generic except block.

4 Using else with try-except

The else block runs only if no exceptions occur in the try block.

try:
num = int(input("Enter a number: "))
print("You entered:", num)
except ValueError:
print("Invalid input! Please enter a number.")
else:
print("No errors occurred. Program executed successfully.")
✅ If no error occurs, the else block executes.

PREPARED BY HARISH YADAV Page 2


PYTHON TRAINING NOTES DREAM A DREAM

5 The finally Block (Always Executes)

The finally block executes whether an exception occurs or not. It is useful for clean-up tasks (e.g.,
closing files or database connections).

try:
file = open("sample.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("Error! File not found.")
finally:
print("Closing the file.")
file.close()

� Explanation

 If sample.txt exists, the file is read.


 If it does not exist, an error message is displayed.
 The finally block closes the file in both cases.

6 Raising Custom Exceptions (raise)

We can force an exception using the raise keyword.

age = int(input("Enter your age: "))

if age < 0:
raise ValueError("Age cannot be negative!")
else:
print("Your age is:", age)
📌 If the user enters a negative number, Python raises a ValueError manually.

PREPARED BY HARISH YADAV Page 3


PYTHON TRAINING NOTES DREAM A DREAM

7 Exception Handling in a Loop (Until Correct Input)

We can use a while loop to keep asking for input until a valid value is entered.

while True:
try:
num = int(input("Enter a number: "))
print("You entered:", num)
break # Exit the loop if input is valid
except ValueError:
print("Invalid input! Please enter a valid number.")
✅ The loop repeats until the user enters a correct number.

8 Multiple Exceptions in One Line

Instead of writing multiple except blocks, we can handle multiple exceptions in one line using a tuple.

try:
num = int(input("Enter a number: "))
result = 10 / num
except (ValueError, ZeroDivisionError):
print("Error! Either invalid input or division by zero.")

PREPARED BY HARISH YADAV Page 4


PYTHON TRAINING NOTES DREAM A DREAM

The math, random, and datetime Modules

Python provides built-in modules that offer additional functionality. Three important modules in Python
are:

1. math module – Provides mathematical functions.


2. random module – Generates random numbers.
3. datetime module – Deals with dates and times.

1 The math Module (Mathematical Functions)

📌 Importing the math Module

To use mathematical functions in Python, we need to import the math module:

import math

📌 Important Functions in math

Function Description Example

math.sqrt(x) Returns square root of x math.sqrt(25) → 5.0

math.pow(x, y) Returns x raised to the power y math.pow(2, 3) → 8.0

math.factorial(x) Returns factorial of x math.factorial(5) → 120

math.ceil(x) Rounds x to the nearest greater integer math.ceil(4.3) → 5

math.floor(x) Rounds x to the nearest smaller integer math.floor(4.7) → 4

math.pi Returns the value of π (pi) math.pi → 3.1415926535

math.e Returns the value of e (Euler's number) math.e → 2.7182818284

PREPARED BY HARISH YADAV Page 5


PYTHON TRAINING NOTES DREAM A DREAM

📌 Example Usage

import math

# Square root
print("Square root of 49:", math.sqrt(49))

# Power function
print("2 raised to power 5:", math.pow(2, 5))

# Factorial
print("Factorial of 6:", math.factorial(6))

# Ceiling and floor


print("Ceiling of 4.3:", math.ceil(4.3))
print("Floor of 4.7:", math.floor(4.7))

# Constants
print("Value of Pi:", math.pi)
print("Value of e:", math.e)

2 The random Module (Generating Random Numbers)

The random module is used for generating random numbers, which is useful in:

 Simulations
 Gaming applications
 Random selection processes

📌 Importing the random Module

import random

📌 Important Functions in random

PREPARED BY HARISH YADAV Page 6


PYTHON TRAINING NOTES DREAM A DREAM

Function Description Example

Generates a random float between 0 and


random.random() random.random() → 0.5673
1

Generates a random integer


random.randint(a, b) random.randint(1, 10) → 7
between a and b (inclusive)

random.uniform(a, Generates a random float


random.uniform(5, 10) → 7.65
b) between a and b

Randomly selects an element from a random.choice(['apple', 'banana',


random.choice(seq)
sequence (list, tuple, string) 'cherry']) → 'banana'

random.shuffle(seq) Shuffles the elements in a list randomly random.shuffle(my_list)

random.sample(seq, Selects k unique elements randomly random.sample(range(1, 10), 3) →


k) from a sequence [2, 9, 5]

📌 Example Usage

import random

# Random float
print("Random float between 0 and 1:", random.random())

# Random integer
print("Random integer between 10 and 50:", random.randint(10, 50))

# Random float between a range


print("Random float between 1 and 10:", random.uniform(1, 10))

# Random choice from a list


fruits = ["Apple", "Banana", "Cherry", "Mango"]

PREPARED BY HARISH YADAV Page 7


PYTHON TRAINING NOTES DREAM A DREAM

print("Randomly selected fruit:", random.choice(fruits))

# Shuffle a list
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print("Shuffled numbers:", numbers)

# Random sample of unique numbers


print("3 random unique numbers from 1 to 10:", random.sample(range(1, 11), 3))

3 The datetime Module (Working with Dates & Times)

The datetime module allows us to work with dates and times.

📌 Importing the datetime Module

import datetime

📌 Getting the Current Date & Time

import datetime

current_time = datetime.datetime.now()
print("Current Date & Time:", current_time)

📌 Extracting Specific Parts

Attribute Description Example

year Returns the year current_time.year → 2025

month Returns the month current_time.month → 3

day Returns the day current_time.day → 9

PREPARED BY HARISH YADAV Page 8


PYTHON TRAINING NOTES DREAM A DREAM

Attribute Description Example

hour Returns the hour current_time.hour → 14

minute Returns the minute current_time.minute → 30

second Returns the second current_time.second → 45

print("Year:", current_time.year)
print("Month:", current_time.month)
print("Day:", current_time.day)
print("Hour:", current_time.hour)
print("Minute:", current_time.minute)
print("Second:", current_time.second)

📌 Creating a Custom Date & Time

We can manually create a specific date using datetime.datetime(year, month, day, hour, minute,
second).

my_birthday = datetime.datetime(2000, 5, 15, 8, 30, 0)


print("My Birthday:", my_birthday)

📌 Formatting Dates (strftime())

We can format dates using strftime(), which converts date objects into readable strings.

formatted_date = current_time.strftime("%d-%m-%Y %H:%M:%S")


print("Formatted Date & Time:", formatted_date)

Format Code Description Example

%Y Full Year 2025

PREPARED BY HARISH YADAV Page 9


PYTHON TRAINING NOTES DREAM A DREAM

Format Code Description Example

%m Month (01-12) 03

%d Day (01-31) 09

%H Hour (00-23) 14

%M Minute (00-59) 30

%S Second (00-59) 45

PREPARED BY HARISH YADAV Page 10

You might also like