python unit 4 and 5
Write a Python program to read a file line by line and display each line separately.
View Algorithm
- 1Define a function `read_file_line_by_line` that takes a file path.
- 2Use a `try...except` block to handle potential `FileNotFoundError`.
- 3Open the specified file in read mode (`'r'`) using a `with` statement.
- 4Iterate through each `line` in the file object.
- 5Inside the loop, print each `line` after removing any trailing newline characters with `.strip()`.
View Code
def read_file_line_by_line(file_path):
with open(file_path, 'r') as file:
for line in file:
print(line.strip())Write a Python program that opens a file and reads its contents. The program should print the entire content of the file on the screen.
View Algorithm
- 1Define a function `read_entire_file` that takes a file path.
- 2Use a `try...except` block to handle `FileNotFoundError`.
- 3Open the file using a `with` statement in read mode (`'r'`).
- 4Call the `file.read()` method to read the entire content into a single string variable.
- 5Print the variable containing the file content.
View Code
def read_entire_file(file_path):
with open(file_path, 'r') as file:
content = file.read()
print(content)Write a Python program to read numbers from a file, calculate their sum, and print the total.
View Algorithm
- 1Define a function `sum_numbers_from_file` with a file path parameter.
- 2Initialize a variable `total` to 0.
- 3Open the file and iterate through each line.
- 4In the loop, convert each line to an integer using `int()` and add it to `total`.
- 5After the loop, print the final `total`.
View Code
def sum_numbers_from_file(file_path):
total = 0
with open(file_path, 'r') as file:
for line in file:
total += int(line.strip())
print(f"The sum is: {total}")Write a Python program to perform basic array operations such as addition, subtraction, multiplication, and division using NumPy arrays.
View Algorithm
- 1Import the `numpy` library as `np`.
- 2Create two NumPy arrays, `array1` and `array2`.
- 3Perform element-wise addition, subtraction, multiplication, and division.
- 4Print the results of each operation.
View Code
import numpy as np
def numpy_operations():
array1 = np.array([10, 20, 30, 40])
array2 = np.array([2, 4, 6, 8])
addition = array1 + array2
subtraction = array1 - array2
multiplication = array1 * array2
division = array1 / array2
print(f"Addition: {addition}")
print(f"Subtraction: {subtraction}")
print(f"Multiplication: {multiplication}")
print(f"Division: {division}")Write a Python program to create a bar chart that displays the sales of different products in a store.
View Algorithm
- 1Import `matplotlib.pyplot` as `plt`.
- 2Create lists for `products` (x-axis) and `sales` (y-axis).
- 3Call `plt.bar()` to create the bar chart.
- 4Add a title and labels for the axes.
- 5Use `plt.show()` to display the chart.
View Code
import matplotlib.pyplot as plt
def plot_sales_bar_chart():
products = ['Laptops', 'Monitors', 'Keyboards', 'Mice']
sales = [120, 85, 150, 200]
plt.bar(products, sales)
plt.title('Product Sales')
plt.xlabel('Products')
plt.ylabel('Sales (Units)')
plt.show()Write a Python program using Matplotlib to plot a simple line graph showing the relationship between years and population growth.
View Algorithm
- 1Import `matplotlib.pyplot` as `plt`.
- 2Create lists for `years` (x-axis) and `population` (y-axis).
- 3Call `plt.plot()` to generate the line graph.
- 4Set the chart title and axis labels.
- 5Use `plt.show()` to display the graph.
View Code
import matplotlib.pyplot as plt
def plot_population_growth():
years = [1950, 1970, 1990, 2010]
population = [2.5, 3.7, 5.3, 7.0]
plt.plot(years, population)
plt.title('Population Growth')
plt.xlabel('Year')
plt.ylabel('Population (Billions)')
plt.show()Write a Python program to create a box plot representing the distribution of marks obtained by students in different subjects.
View Algorithm
- 1Import `matplotlib.pyplot` as `plt`.
- 2Create lists of marks for several subjects.
- 3Combine these lists into a single list of lists.
- 4Call `plt.boxplot()` with the data and labels.
- 5Add a title and y-axis label.
- 6Use `plt.show()` to display the plot.
View Code
import matplotlib.pyplot as plt
def plot_marks_distribution():
math_marks = [65, 78, 82, 85, 88, 90, 92, 95, 100]
science_marks = [55, 60, 70, 75, 80, 85, 88, 90, 98]
data = [math_marks, science_marks]
subjects = ['Math', 'Science']
plt.boxplot(data, labels=subjects)
plt.title('Distribution of Marks')
plt.ylabel('Marks Obtained')
plt.show()Write a Python program to draw a pie chart showing the percentage distribution of expenses (like rent, food, travel, and entertainment).
View Algorithm
- 1Import `matplotlib.pyplot` as `plt`.
- 2Create lists for `expenses` (values) and `categories` (labels).
- 3Call `plt.pie()` to create the chart, using `autopct` to show percentages.
- 4Add a title.
- 5Use `plt.show()` to display the chart.
View Code
import matplotlib.pyplot as plt
def plot_expenses_pie_chart():
expenses = [800, 450, 200, 350]
categories = ['Rent', 'Food', 'Travel', 'Entertainment']
plt.pie(expenses, labels=categories, autopct='%1.1f%%')
plt.title('Monthly Expenses')
plt.show()Write a program to handle division by zero which accepts two numbers and displays an error if the denominator is zero.
View Algorithm
- 1Define a function `safe_divide` that accepts a numerator and a denominator.
- 2Use a `try` block for the division operation.
- 3If successful, print the result.
- 4Add an `except ZeroDivisionError` block to catch the error and print a message.
View Code
def safe_divide(numerator, denominator):
try:
result = numerator / denominator
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")Write a program to handle invalid input (ValueError) and ask the user for a number and handle non-numeric input.
View Algorithm
- 1Define a function `get_number_from_user`.
- 2Inside a `try` block, prompt the user for input and convert it to an integer.
- 3If successful, print the number.
- 4Add an `except ValueError` block to handle non-numeric input and print an error.
View Code
def get_number_from_user():
try:
number = int(input("Enter a number: "))
print(f"You entered: {number}")
except ValueError:
print("Error: Invalid input. Please enter a number.")Write a program to open a file and handle FileNotFoundError, and try to open a file that may not exist.
View Algorithm
- 1Define a function `open_a_file` that accepts a file path.
- 2Use a `try` block to open the file in read mode.
- 3If successful, print the file content.
- 4Add an `except FileNotFoundError` block to print an error if the file does not exist.
View Code
def open_a_file(file_path):
try:
with open(file_path, 'r') as file:
print("File opened successfully.")
print(file.read())
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")Write a program to find the factorial of a number using the math.factorial() function.
View Algorithm
- 1Import the `math` module.
- 2Define a function that takes a number `n`.
- 3Return the result of `math.factorial(n)`.
View Code
import math
def calculate_factorial(n):
return math.factorial(n)Write a program to calculate the area of a circle using the math.pi constant.
View Algorithm
- 1Import the `math` module.
- 2Define a function that takes the `radius`.
- 3Calculate the area using the formula `pi * r^2`.
- 4Return the result.
View Code
import math
def area_of_circle(radius):
return math.pi * (radius ** 2)Write a program to compute the power of a number using the math.pow() function.
View Algorithm
- 1Import the `math` module.
- 2Define a function that takes a `base` and `exponent`.
- 3Return the result of `math.pow(base, exponent)`.
View Code
import math
def power_of_number(base, exponent):
return math.pow(base, exponent)Write a program to calculate the cosine, sine, and tangent of an angle using the math module.
View Algorithm
- 1Import the `math` module.
- 2Define a function that takes an angle in degrees.
- 3Convert the angle to radians using `math.radians()`.
- 4Calculate the cosine, sine, and tangent.
- 5Return the three values.
View Code
import math
def trig_functions(angle_degrees):
angle_radians = math.radians(angle_degrees)
cos_val = math.cos(angle_radians)
sin_val = math.sin(angle_radians)
tan_val = math.tan(angle_radians)
return cos_val, sin_val, tan_valCreate a module greetings.py with two functions — morning_greeting(name) and evening_greeting(name). Import this module into a main program and use the functions.
View Algorithm
- 1Create a file named `greetings.py`.
- 2Define `morning_greeting(name)` and `evening_greeting(name)` in it.
- 3Create a `main.py` file.
- 4Import the `greetings` module.
- 5Call the functions from the module.
View Code
# greetings.py
def morning_greeting(name):
return f"Good morning, {name}!"
def evening_greeting(name):
return f"Good evening, {name}!"
# main.py
# import greetings
# print(greetings.morning_greeting("Alice"))
# print(greetings.evening_greeting("Bob"))Write a Python program that creates a user-defined module named calculator.py containing functions for addition, subtraction, multiplication, and division.
View Algorithm
- 1Create a file `calculator.py`.
- 2Define functions for `add`, `subtract`, `multiply`, and `divide`.
- 3In `divide`, handle the case where the divisor is zero.
- 4This module can now be imported and used in other programs.
View Code
# calculator.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Error: Cannot divide by zero."
return a / bWrite a Python program to demonstrate the concept of classes and objects.
View Algorithm
- 1Define a class `Dog` with an `__init__` method.
- 2The `__init__` method should accept `name` and `breed` as parameters.
- 3Define a method `bark` that returns a string.
- 4Create an instance (object) of the `Dog` class.
- 5Access the object's attributes and call its methods.
View Code
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
return "Woof!"
my_dog = Dog("Buddy", "Golden Retriever")
# print(my_dog.name) -> "Buddy"
# print(my_dog.bark()) -> "Woof!"Create a Python class Book with attributes title, author, and price. Define a method display_details() to print the details of the book.
View Algorithm
- 1Define a class `Book`.
- 2In `__init__`, initialize `title`, `author`, and `price`.
- 3Define a method `display_details` that prints the attributes in a formatted way.
- 4Create an object of the `Book` class and call its method.
View Code
class Book:
def __init__(self, title, author, price):
self.title = title
self.author = author
self.price = price
def display_details(self):
print(f"Title: {self.title}, Author: {self.author}, Price: ${self.price}")Write a Python program to define a class Car with attributes brand, model, and price. Include a method to display car details. Create multiple car objects.
View Algorithm
- 1Define a class `Car` with `brand`, `model`, and `price` attributes.
- 2Create a method `display_details` to print the car's information.
- 3Instantiate multiple `Car` objects with different details.
- 4Call the `display_details` method for each object.
View Code
class Car:
def __init__(self, brand, model, price):
self.brand = brand
self.model = model
self.price = price
def display_details(self):
print(f"Brand: {self.brand}, Model: {self.model}, Price: ${self.price}")Write a Python program to define a class Employee with attributes name, id, and salary. Include a method to display employee details.
View Algorithm
- 1Define an `Employee` class.
- 2Initialize `name`, `id`, and `salary` in the constructor.
- 3Create a `display_details` method to show the employee's data.
- 4Create objects of the `Employee` class and display their details.
View Code
class Employee:
def __init__(self, name, id, salary):
self.name = name
self.id = id
self.salary = salary
def display_details(self):
print(f"Name: {self.name}, ID: {self.id}, Salary: ${self.salary}")Write a Python program to define a class Teacher with attributes name, subject, and experience. Add a method show_info() to display the teacher's details.
View Algorithm
- 1Define a `Teacher` class with `name`, `subject`, and `experience`.
- 2Create a `show_info` method to print the teacher's details.
- 3Instantiate a `Teacher` object and call the method.
View Code
class Teacher:
def __init__(self, name, subject, experience):
self.name = name
self.subject = subject
self.experience = experience
def show_info(self):
print(f"Name: {self.name}, Subject: {self.subject}, Experience: {self.experience} years")Create a Python class Mobile with attributes brand, model, and price. Define a method display() to show mobile details. Create and display data for three mobiles.
View Algorithm
- 1Define a `Mobile` class with `brand`, `model`, and `price`.
- 2Implement a `display` method to print the attributes.
- 3Create three different `Mobile` objects.
- 4Call the `display` method for each of the three objects.
View Code
class Mobile:
def __init__(self, brand, model, price):
self.brand = brand
self.model = model
self.price = price
def display(self):
print(f"Brand: {self.brand}, Model: {self.model}, Price: ${self.price}")Write a Python program to demonstrate method overloading (using default arguments).
View Algorithm
- 1Define a class, for example, `Calculator`.
- 2Create a method `add` that takes two required arguments (`a`, `b`) and one optional argument (`c` with a default value of 0).
- 3The method returns the sum of the arguments.
- 4This allows the `add` method to be called with two or three numbers.
View Code
class Calculator:
def add(self, a, b, c=0):
return a + b + cWrite a Python program to demonstrate method overriding.
View Algorithm
- 1Create a base class `Animal` with a method `speak`.
- 2Create a derived class `Cat` that inherits from `Animal`.
- 3Redefine the `speak` method in the `Cat` class to return a different string.
- 4An object of the `Cat` class will use its own `speak` method.
View Code
class Animal:
def speak(self):
return "Some generic animal sound"
class Cat(Animal):
def speak(self):
return "Meow"Write a Python program to demonstrate polymorphism using a common interface.
View Algorithm
- 1Define two classes, `Dog` and `Cat`, both with a `speak` method.
- 2Define a function `make_animal_speak` that takes an animal object as an argument.
- 3This function calls the `speak` method on the object it receives.
- 4The function works with any object that has a `speak` method, demonstrating polymorphism.
View Code
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
def make_animal_speak(animal):
print(animal.speak())Create a Function to add two numbers.
View Algorithm
- 1Define a function `add_two_numbers` that accepts two parameters, `a` and `b`.
- 2Inside the function, return the sum of `a` and `b`.
View Code
def add_two_numbers(a, b):
return a + bCreate a Function to find factorial of a number.
View Algorithm
- 1Define a recursive function `factorial` that takes a number `n`.
- 2Set the base case: if `n` is 0, return 1.
- 3Otherwise, return `n` multiplied by `factorial(n-1)`.
View Code
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)Create a Function to check if a number is even or odd.
View Algorithm
- 1Define a function `is_even_or_odd` that takes a number.
- 2Use the modulo operator (`%`) to check if the number is divisible by 2.
- 3Return 'Even' if the remainder is 0, otherwise return 'Odd'.
View Code
def is_even_or_odd(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"Write a program to calculate square root using built-in math.sqrt().
View Algorithm
- 1Import the `math` module.
- 2Define a function that takes a number.
- 3Return the result of `math.sqrt(number)`.
View Code
import math
def calculate_square_root(number):
return math.sqrt(number)Write a program to find the maximum and minimum from a list (max(), min()).
View Algorithm
- 1Define a function that accepts a list of numbers.
- 2Use the built-in `max()` function to find the maximum value.
- 3Use the built-in `min()` function to find the minimum value.
- 4Return both the maximum and minimum values.
View Code
def find_max_min(numbers):
max_num = max(numbers)
min_num = min(numbers)
return max_num, min_num