Python Notes Part3
Python Notes Part3
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.
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
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
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.
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 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.
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.
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.")
Python provides built-in modules that offer additional functionality. Three important modules in Python
are:
import math
📌 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))
# Constants
print("Value of Pi:", math.pi)
print("Value of e:", math.e)
The random module is used for generating random numbers, which is useful in:
Simulations
Gaming applications
Random selection processes
import random
📌 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))
# Shuffle a list
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print("Shuffled numbers:", numbers)
import datetime
import datetime
current_time = datetime.datetime.now()
print("Current Date & Time:", current_time)
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)
We can manually create a specific date using datetime.datetime(year, month, day, hour, minute,
second).
We can format dates using strftime(), which converts date objects into readable strings.
%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