Objective 35- Write a Python class named Circle constructed by a radius and
two methods which will compute the area and the perimeter of a circle.
Code:
class Circle:
def __init__(self, radius):
[Link] = radius
def area(self):
return 3.14159 * [Link] ** 2
def perimeter(self):
return 2 * 3.14159 * [Link]
user_radius = float(input("Enter the radius of the circle: "))
circle = Circle(user_radius)
print("Radius:", [Link])
print("Area:", [Link]())
print("Perimeter:", [Link]())
Output:
Enter the radius of the circle: 5
Radius: 5.0
Area: 78.53975
Perimeter: 31.4159
Atharv Joshi
Objective 36- Write a Python class named Rectangle constructed by a length
and width and a method which will compute the area of a rectangle.
Code:
class Circle:
def __init__(self, radius):
[Link] = radius
def area(self):
return 3.14159 * [Link] ** 2
def perimeter(self):
return 2 * 3.14159 * [Link]
user_radius = float(input("Enter the radius of the circle: "))
circle = Circle(user_radius)
print("Radius:", [Link])
print("Area:", [Link]())
print("Perimeter:", [Link]())
Output:
Enter the length of the rectangle: 10
Enter the width of the rectangle: 5
Length: 10.0
Width: 5.0
Area: 50.0
Atharv Joshi
Objective 37- Write a Python class to reverse a string word by word. • Input
string: ’hello .py' • Expected Output: '.py hello'.
Code:
class StringReverser:
def reverse_words(self, input_string):
return ' '.join(input_string.split()[::-1])
input_string = input("Enter a string: ")
reverser = StringReverser()
output_string = reverser.reverse_words(input_string)
print("Original string:", input_string)
print("Reversed string:", output_string)
Output:
Enter a string: Hello world this is Python
Original string: Hello world this is Python
Reversed string: Python is this world Hello
Objective 38- Given a .txt file that has a list of a bunch of names, count how
many of each name there are in the file, and print out the results to the screen.
Code:
from collections import Counter
def count_names(file_path):
try:
with open(file_path, 'r') as file:
names = [Link]().splitlines()
name_counts = Counter(names)
print("Name Counts:")
for name, count in name_counts.items():
print(f"{name}: {count}")
except FileNotFoundError:
print("The file was not found.")
except Exception as e:
print(f"An error occurred: {e}")
file_path = "D:/[Link]"
Atharv Joshi
count_names(file_path)
Output:
Name Counts:
Alice: 3
Bob: 2
Charlie: 1
Objective 39- Write a python program to remove newline character from file
Code:
def write_input_to_file(file_path):
print("Enter text line by line. Type 'done' when you are finished:")
with open(file_path, 'w') as file:
while True:
line = input()
if [Link]() == 'done':
break
[Link](line + '\n')
def remove_newlines_from_file(file_path):
with open(file_path, 'r') as file:
content = [Link]()
modified_content = [Link]('\n', '')
with open(file_path, 'w') as file:
[Link](modified_content)
def display_file_contents(file_path):
with open(file_path, 'r') as file:
content = [Link]() # Read the file content
print("\nContents of the file after removing newlines:")
print(content)
file_path = '[Link]'
write_input_to_file(file_path)
remove_newlines_from_file(file_path)
display_file_contents(file_path)count_names(file_path)
Atharv Joshi
Output:
Enter text line by line. Type 'done' when you are finished:
Hello
World
Python is great
done
Contents of the file after removing newlines:
HelloWorldPython is great
Objective 40- Write a Python program to combine each line from first file
with the corresponding line in second file
Code:
def take_input_and_save(file_path):
print("Enter text for " + file_path + ". Type 'done' when you are finished:")
with open(file_path, 'w') as file:
while True:
line = input()
if [Link]() == 'done':
break
[Link](line + '\n')
def combine_files(file1_path, file2_path, output_file_path):
with open(file1_path, 'r') as file1, open(file2_path, 'r') as file2, open(output_file_path, 'w')
as output_file:
for line1, line2 in zip(file1, file2): # Combine lines from both files
output_file.write([Link]() + ' ' + [Link]() + '\n')
def display_combined_output(output_file_path):
with open(output_file_path, 'r') as output_file:
combined_content = output_file.read()
print("\nCombined Output:")
print(combined_content)
# Get file paths from the user
file1_path = input("Enter the name of the 1st file (e.g., [Link]): ")
file2_path = input("Enter the name of the 2nd file (e.g., [Link]): ")
output_file_path = input("Enter the name for the output file (e.g., [Link]): ")
# Perform operations
Atharv Joshi
take_input_and_save(file1_path)
take_input_and_save(file2_path)
combine_files(file1_path, file2_path, output_file_path)
print("\nLines combined into " + output_file_path)
display_combined_output(output_file_path)
Output:
Enter text for [Link]. Type 'done' when you are finished:
Hello
Good morning
Done
Enter text for [Link]. Type 'done' when you are finished:
World
Everyone
Done
Lines combined into [Link]
Combined Output:
Hello World
Good morning Everyone
Objective 41- Write a python program to copy the content of the file to
another file
Code:
def create_and_copy_file():
try:
# Prompt the user for file names
source_file = input("Enter the source file name (with extension): ")
destination_file = input("Enter the destination file name (with extension): ")
# Collect content for the source file
print("\nEnter the content you want to write in the source file (type 'DONE' to finish):")
lines = []
while True:
line = input()
Atharv Joshi
if [Link]() == 'DONE':
break
[Link](line)
# Write to the source file
with open(source_file, 'w') as src:
[Link]('\n'.join(lines))
# Read from the source file
with open(source_file, 'r') as src:
content = [Link]()
print("\nContents of the source file:")
print(content)
# Write to the destination file
with open(destination_file, 'w') as dest:
[Link](content)
print(f"File copied successfully from {source_file} to {destination_file}.")
except Exception as e:
print(f"An error occurred: {e}")
# Call the function
create_and_copy_file()
Output:
Enter the source file name (with extension): [Link]
Enter the destination file name (with extension): [Link]
Enter the content you want to write in the source file (type 'DONE' to finish):
Hello
This is a test file.
DONE
Contents of the source file:
Hello
This is a test file.
File copied successfully from [Link] to [Link].
Atharv Joshi
Objective 42-WAP to define Student class and create an object to it. Also, we
will call the method and display the student’s details
Code:
class Student:
def __init__(self, name, age, roll_number):
[Link] = name
[Link] = age
self.roll_number = roll_number
def display_details(self):
print("Student Details:")
print("Name: {}".format([Link]))
print("Age: {}".format([Link]))
print("Roll Number: {}".format(self.roll_number))
name = input("Enter the student's name: ")
age = input("Enter the student's age: ")
roll_number = input("Enter the student's roll number: ")
student = Student(name, age, roll_number)
student.display_details()
Output:
Enter the student's name: John Doe
Enter the student's age: 20
Enter the student's roll number: 12345
Student Details:
Name: John Doe
Age: 20
Roll Number: 12345
Atharv Joshi
Objective 43- WAP To create a static method that counts the number of
instants created for a class
Code:
class Student:
instance_count = 0 # Class variable to track the number of instances
def __init__(self, name, age, roll_number):
[Link] = name
[Link] = age
self.roll_number = roll_number
Student.instance_count += 1 # Increment the instance count whenever a new student is
created
@classmethod
def get_instance_count(cls):
return cls.instance_count # Return the number of instances created
def display_details(self):
print("Student Details:")
print("Name: {}".format([Link]))
print("Age: {}".format([Link]))
print("Roll Number: {}".format(self.roll_number))
# Creating instances of the Student class
student1 = Student("Alice", 21, "101")
student2 = Student("Bob", 22, "102")
student3 = Student("Charlie", 23, "103")
# Display details of each student
student1.display_details()
student2.display_details()
student3.display_details()
# Display the total number of instances created
print("\nTotal number of Student instances created:", Student.get_instance_count())
Atharv Joshi
Output:
Student Details:
Name: Alice
Age: 21
Roll Number: 101
Student Details:
Name: Bob
Age: 22
Roll Number: 102
Student Details:
Name: Charlie
Age: 23
Roll Number: 103
Total number of Student instances created: 3
Objective 44 WAP to create a Bank class where deposits and withdraw can be
handled by using instance methods.
Code:
class Bank:
def __init__(self, initial_balance=0):
[Link] = initial_balance # Initialize balance with a default or provided amount
def deposit(self, amount):
[Link] += amount # Add the deposit amount to the balance
print("Deposited: $", amount)
def withdraw(self, amount):
if amount <= [Link]: # Check if enough balance is available
[Link] -= amount # Subtract the withdrawal amount from the balance
print("Withdrawn: $", amount)
else:
print("Insufficient funds.") # Print a message if funds are insufficient
Atharv Joshi
def get_balance(self):
return [Link] # Return the current balance
# Create a bank account with an initial balance of $1000
account = Bank(1000)
# Perform operations
[Link](500) # Deposit $500
[Link](200) # Withdraw $200
# Print the current balance
print("Current balance: $", account.get_balance
Output:
Deposited: $ 500
Withdrawn: $ 200
Current balance: $ 1300
Objective 45- WAP showing single inheritance in which two sub classes are
derived from a single base class.
Code:
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
return "I am an animal."
class Dog(Animal):
def speak(self):
return "Woof! My name is " + [Link]
class Cat(Animal):
def speak(self):
return "Meow! My name is " + [Link]
Atharv Joshi
# Creating instances of Dog and Cat
dog = Dog("Buddy")
cat = Cat("Whiskers")
# Printing the speak method outputs
print([Link]()) # Woof! My name is Buddy
print([Link]()) # Meow! My name is Whiskers
Output:
Woof! My name is Buddy
Meow! My name is Whiskers
Objective 46 WAP to implement multiple inheritance using two base classes
Code:
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
return "I am an animal."
class Color:
def __init__(self, color):
[Link] = color
def describe_color(self):
return f"My color is {[Link]}."
class Dog(Animal, Color):
def __init__(self, name, color):
Animal.__init__(self, name)
Color.__init__(self, color)
def introduce(self):
return f"{[Link]()} I am a {[Link]} dog, and my name is {[Link]}."
Atharv Joshi
dog = Dog("Buddy", "brown")
print([Link]())
print([Link]())
print(dog.describe_color())
Output:
I am an animal. I am a brown dog, and my name is Buddy.
I am an animal.
My color is brown.
Objective 47- WAP to show method overloading to find sum of two or three
numbers..
Code:
class Calculator:
def add(self, a, b, c=0):
return a + b + c
calculator = Calculator()
sum_two = [Link](5, 10)
print("Sum of two numbers (5 + 10):", sum_two)
sum_three = [Link](5, 10, 15)
print("Sum of three numbers (5 + 10 + 15):", sum_three)
Output:
Sum of two numbers (5 + 10): 15
Sum of three numbers (5 + 10 + 15): 30
Atharv Joshi
Objective 48 WAP to Create a 3×3 numpy array of all True's.
Code:
import numpy as np
array = [Link]((3, 3), dtype=bool)
print(array)
Output:
[[ True True True]
[ True True True]
[ True True True]]
Objective 49 : WAP to Replace all odd numbers in arr with -1
a. Input ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).
def replace_odds_with_minus_one(arr):
return [-1 if x % 2 != 0 else x for x in arr]
input_array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
output_array = replace_odds_with_minus_one(input_array)
print(output_array)
Output:
[0, -1, 2, -1, 4, -1, 6, -1, 8, -1]
Objective 50 : WAP to Convert a ID array to a 2D array with 2 rows
a. Input: np. arrange (10)
import numpy as np
arr = [Link](10)
arr_2d = [Link](2, -1)
print(arr_2d)
Output:
[[0 1 2 3 4]
[5 6 7 8 9]]
Atharv Joshi
Objective 51 : WAP to Get the common items between a and b
Input:
import numpy as np
def common_items(a, b):
return np.intersect1d(a, b)
a = [Link]([1, 2, 3, 4, 5])
b = [Link]([4, 5, 6, 7, 8])
result = common_items(a, b)
print(result)
Output:
[4, 5]
Objective 52 : Write a program which generates a random password for the
user. Ask the user how long they want their password to be, and how many
letters and numbers they want in their password. Have a mix of upper and
lowercase letters, as well as numbers and symbols. The password should be a
minimum of 6 characters long.
import random
import string
def generate_password():
length = int(input("Enter the length of the password (minimum 6): "))
if length < 6:
print("Password length should be at least 6.")
return
num_letters = int(input("Enter number of letters: "))
num_numbers = int(input("Enter number of numbers: "))
num_symbols = length - (num_letters + num_numbers)
if num_symbols < 0:
print("The sum of letters and numbers exceeds the total password length.")
return
letters = [Link](string.ascii_letters, k=num_letters)
numbers = [Link]([Link], k=num_numbers)
Atharv Joshi
symbols = [Link]([Link], k=num_symbols)
password_list = letters + numbers + symbols
[Link](password_list)
password = ''.join(password_list)
print("Generated Password:", password)
generate_password()
Output:
Enter the length of the password (minimum 6): 12
Enter number of letters: 6
Enter number of numbers: 3
Generated Password: F3aS8e$Zr1Gv
Atharv Joshi
Output:
Enter text line by line. Type 'done' when you are finished:
Hello
World
Python is great
done
Contents of the file after removing newlines:
HelloWorldPython is great
Atharv Joshi