Python Programs
Python Programs
# Example usage
try:
num1 = float(input("Enter the numerator: "))
num2 = float(input("Enter the denominator: "))
result = divide(num1, num2)
print("Result:", result)
except DivisionByZeroError as e:
print("Error:", e)
except ValueError:
print("Invalid input. Please enter numeric values.")
3. Write a python program to copy the content of one file into another.
def copy_file(source_file, destination_file):
try:
with open(source_file, 'r') as source:
with open(destination_file, 'w') as destination:
for line in source:
destination.write(line)
print("File copied successfully.")
except FileNotFoundError:
print("Error: One or both files not found.")
except IOError:
print("Error: An error occurred while copying the file.")
# Example usage
source_file = input("Enter the path of the source file: ")
destination_file = input("Enter the path of the destination file: ")
copy_file(source_file, destination_file)
# Example usage
file_path = input("Enter the path of the file to read: ")
read_file(file_path)
# Example usage
file_path = input("Enter the path of the file: ")
count_words(file_path)
def create_directory(directory_path):
try:
os.makedirs(directory_path)
print("Directory created successfully:", directory_path)
except FileExistsError:
print("Error: Directory already exists.")
except OSError:
print("Error: An error occurred while creating the directory.")
# Example usage
directory_path = input("Enter the path for the new directory: ")
create_directory(directory_path)
7. Write a python program to write multiple lines to a text file using writelines() method.
def write_lines(file_path, lines):
try:
with open(file_path, 'w') as file:
file.writelines(lines)
print("Lines written successfully to the file.")
except IOError:
print("Error: An error occurred while writing to the file.")
# Example usage
file_path = input("Enter the path of the file: ")
lines = []
num_lines = int(input("Enter the number of lines to write: "))
for i in range(num_lines):
line = input(f"Enter line {i+1}: ")
lines.append(line + '\n')
write_lines(file_path, lines)
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Woof!"
class Cat(Animal):
def sound(self):
return "Meow!"
class Vehicle(ABC):
def __init__(self, brand):
self.brand = brand
@abstractmethod
def start(self):
pass
class Car(Vehicle):
def start(self):
return f"{self.brand} car has started."
class Bike(Vehicle):
def start(self):
return f"{self.brand} bike has started."
class Dog(Animal):
def sound(self):
print("The dog barks.")
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
12. Write a program to plot the points in bar format using matplotlib.
import matplotlib.pyplot as plt
# Example usage
x = [1, 2, 3, 4, 5]
y = [10, 7, 5, 3, 8]
plot_points(x, y)
import math
# Example usage
year = 2024
if is_leap_year(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
Note -: using function prepare for all basic program like prime number , Armstrong , Fibonacci series
etc .
# Convert to uppercase
print("Uppercase:", text.upper())
# Convert to lowercase
print("Lowercase:", text.lower())
# Accessing values
print("Name:", student['name'])
print("Age:", student.get('age'))
# Updating values
student['age'] = 26
student['major'] = 'Information Technology'
print("Updated Dictionary:", student)
# Union of sets
union_set = set1.union(set2)
print("Union:", union_set)
# Intersection of sets
intersection_set = set1.intersection(set2)
print("Intersection:", intersection_set)
# Accessing elements
print("First element:", fruits[0])
print("Last element:", fruits[-1])
# Modifying elements
fruits[1] = 'orange'
print("Modified list:", fruits)
# Appending elements
fruits.append('grape')
print("List after appending:", fruits)
# Removing elements
fruits.remove('cherry')
print("List after removing:", fruits)
# Inserting elements
fruits.insert(1, 'mango')
print("List after inserting:", fruits)
# Counting occurrences
count = fruits.count('apple')
print("Count of 'apple':", count)
# Sorting elements
fruits.sort()
print("Sorted list:", fruits)
# Reversing elements
fruits.reverse()
print("Reversed list:", fruits)