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

Python Programs

The document contains a collection of Python programs demonstrating various programming concepts such as user-defined exceptions, file handling, inheritance, data abstraction, and built-in methods for strings, dictionaries, sets, and lists. Each program includes example usage and error handling to illustrate best practices in Python programming. The document serves as a comprehensive guide for beginners to learn and implement fundamental Python programming techniques.

Uploaded by

Shahjad pathan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Python Programs

The document contains a collection of Python programs demonstrating various programming concepts such as user-defined exceptions, file handling, inheritance, data abstraction, and built-in methods for strings, dictionaries, sets, and lists. Each program includes example usage and error handling to illustrate best practices in Python programming. The document serves as a comprehensive guide for beginners to learn and implement fundamental Python programming techniques.

Uploaded by

Shahjad pathan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Python Programs

1. Write a program to create user defined exception for divided by zero .


class DivisionByZeroError(Exception):
def __init__(self, message="Division by zero is not allowed"):
self.message = message
super().__init__(self.message)

# Function to perform division


def divide(a, b):
if b == 0:
raise DivisionByZeroError()
return a / b

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

2. Write a program to handle exception for zero division error.


try:
# Code that may raise an exception
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: 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)

4. Write a python program to open and read a file.


def read_file(file_path):
try:
with open(file_path, 'r') as file:
content = file.read()
print("File content:\n", content)
except FileNotFoundError:
print("Error: File not found.")
except IOError:
print("Error: An error occurred while reading the file.")

# Example usage
file_path = input("Enter the path of the file to read: ")
read_file(file_path)

5. Write a python program to count the number of words in a file.


def count_words(file_path):
try:
with open(file_path, 'r') as file:
content = file.read()
word_count = len(content.split())
print("Number of words in the file:", word_count)
except FileNotFoundError:
print("Error: File not found.")
except IOError:
print("Error: An error occurred while reading the file.")

# Example usage
file_path = input("Enter the path of the file: ")
count_words(file_path)

6. Write a python program to create a new directory .


import os

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)

8. Write a simple program to implement inheritance in python .


class Animal:
def __init__(self, name):
self.name = name

def sound(self):
pass

class Dog(Animal):
def sound(self):
return "Woof!"

class Cat(Animal):
def sound(self):
return "Meow!"

# Create instances of Dog and Cat


dog = Dog("Buddy")
cat = Cat("Whiskers")
# Call the sound method of Dog and Cat
print(dog.name + ": " + dog.sound())
print(cat.name + ": " + cat.sound())

9. Write a program for data abstraction in python .


from abc import ABC, abstractmethod

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

# Creating instances of Car and Bike


car = Car("Toyota")
bike = Bike("Honda")

# Calling the start method for Car and Bike


print(car.start())
print(bike.start())

10. Write a simple python program for method overriding.


class Animal:
def sound(self):
print("The animal makes a sound.")

class Dog(Animal):
def sound(self):
print("The dog barks.")

# Create instances of Animal and Dog


animal = Animal()
dog = Dog()

# Call the sound method of Animal and Dog


animal.sound()
dog.sound()
11. Write a simple python program for class and object .
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# Create an instance of the Person class


person = Person("Alice", 25)

# Call the greet method of the person object


person.greet()

12. Write a program to plot the points in bar format using matplotlib.
import matplotlib.pyplot as plt

def plot_points(x, y):


plt.bar(x, y)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Points in Bar Format')
plt.show()

# Example usage
x = [1, 2, 3, 4, 5]
y = [10, 7, 5, 3, 8]

plot_points(x, y)

13. Write a basic program using pandas


import pandas as pd

# Create a dictionary of data


data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 35, 40],
'City': ['New York', 'London', 'Paris', 'Tokyo']}

# Create a DataFrame from the data


df = pd.DataFrame(data)

# Print the DataFrame


print(df)
14. Write a basic program for numpy.
import numpy as np

# Create a NumPy array


arr = np.array([1, 2, 3, 4, 5])

# Print the array


print("Array:", arr)

# Perform arithmetic operations on the array


print("Sum:", np.sum(arr))
print("Mean:", np.mean(arr))
print("Max:", np.max(arr))
print("Min:", np.min(arr))

15. Write a basic program for scipy in python.


import numpy as np
from scipy import optimize

# Define a function to optimize


def f(x):
return np.sin(x) + 0.5 * x

# Find the minimum of the function using the BFGS algorithm


result = optimize.minimize(f, x0=2)

# Print the result


print(result)

16. Write a program for built-in module .


import datetime

# Get the current date and time


current_datetime = datetime.datetime.now()

# Print the current date and time


print("Current Date and Time:", current_datetime)

import math

# Calculate the square root of a number


number = 16
square_root = math.sqrt(number)

# Print the square root


print("Square Root of", number, ":", square_root)
17. Write a python program to create a function to check whether a given year is leap or
not .
def is_leap_year(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False

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

18. Write a program for string built-in methods .


# String
text = "Hello, World!"

# Length of the string


print("Length:", len(text))

# Convert to uppercase
print("Uppercase:", text.upper())

# Convert to lowercase
print("Lowercase:", text.lower())

# Capitalize the first letter


print("Capitalized:", text.capitalize())

# Count occurrences of a substring


substring = "l"
print("Count of '", substring, "':", text.count(substring))

# Check if the string starts with a specific substring


substring = "Hello"
print("Starts with '", substring, "':", text.startswith(substring))

# Check if the string ends with a specific substring


substring = "World!"
print("Ends with '", substring, "':", text.endswith(substring))

# Replace a substring with another


old_substring = "World"
new_substring = "Universe"
new_text = text.replace(old_substring, new_substring)
print("Replaced '", old_substring, "' with '", new_substring, "':", new_text)

# Split the string into a list of substrings


words = text.split()
print("Split into words:", words)

19. Write a program for built-in dictionary methods .


# Dictionary
student = {
'name': 'Alice',
'age': 25,
'university': 'ABC University',
'major': 'Computer Science'
}

# Accessing values
print("Name:", student['name'])
print("Age:", student.get('age'))

# Updating values
student['age'] = 26
student['major'] = 'Information Technology'
print("Updated Dictionary:", student)

# Adding new key-value pairs


student['gpa'] = 3.8
print("Updated Dictionary with GPA:", student)

# Removing a key-value pair


del student['university']
print("Dictionary after Removing 'university':", student)

# Checking if a key exists


if 'age' in student:
print("'age' exists in the dictionary.")
else:
print("'age' does not exist in the dictionary.")

# Getting all keys


keys = student.keys()
print("Keys:", keys)

# Getting all values


values = student.values()
print("Values:", values)

# Getting all key-value pairs


items = student.items()
print("Key-Value Pairs:", items)

20. Write a program for basic set operation.


# Define sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Union of sets
union_set = set1.union(set2)
print("Union:", union_set)

# Intersection of sets
intersection_set = set1.intersection(set2)
print("Intersection:", intersection_set)

# Difference between sets


difference_set = set1.difference(set2)
print("Set1 - Set2:", difference_set)

# Symmetric difference between sets


symmetric_difference_set = set1.symmetric_difference(set2)
print("Symmetric Difference:", symmetric_difference_set)

# Check if a set is a subset of another set


subset_check = set1.issubset(set2)
print("Set1 is a subset of Set2:", subset_check)

# Check if a set is a superset of another set


superset_check = set1.issuperset(set2)
print("Set1 is a superset of Set2:", superset_check)

21. Write a program for basic list built-in methods.


# Define a list
fruits = ['apple', 'banana', 'cherry', 'durian']

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

You might also like