Untitled
Untitled
1.4 Print all the numbers between 100 to 200 which are divisible by 4 and 7
2.2 Check the presence/absence of a given value in the list; display total number
of occurrences along with the index positions of each occurrence.
my_list = [3, 5, 6, 2, 8, 3, 9, 3, 7]
search_value = 3
# find the occurrences of the search value and their index positions
occurrences = [i for i, x in enumerate(my_list) if x ==
search_value]
num_occurrences = len(occurrences)
# check if the search value is present in the list
if num_occurrences == 0:
print("The search value is not present in the list.")
else:
print("The search value is present in the list.")
print("Total number of occurrences:", num_occurrences)
print("Index positions of occurrences:", occurrences)
2.3 Perform sorting of list elements; Press 1 for ascending order and, Press 2 for
descending order
my_list = [5, 2, 8, 4, 9, 3]
# take user input for the sorting order
sorting_order = int(input("Enter 1 for ascending order or 2 for descending order: "))
# perform the sorting based on user input
if sorting_order == 1:
my_list.sort()
print("List elements in ascending order:", my_list)
elif sorting_order == 2:
my_list.sort(reverse=True)
print("List elements in descending order:", my_list)
else:
print("Invalid input! Please enter either 1 or 2.")
import datetime
date_string = input("Enter a date in YYYY-MM-DD format: ")
date_object = datetime.datetime.strptime(date_string, '%Y-%m-%d')
month_name = date_object.strftime("%B")
print("Month name:", month_name)
[3] Python – User Defined Functions (UDF)
Write Python program using UDF to....
3.1 Calculate library fine based on 2 conditions, a) Book return date and b) Book
condition
import datetime
# take user input for the book return date in YYYY-MM-DD format
return_date_string = input("Enter the book return date in YYYY-MM-DD
format: ")
return_date = datetime.datetime.strptime(return_date_string, '%Y-%m-
%d').date()
# take user input for the book condition
book_condition = input("Enter the book condition (good or damaged):
")
# define the fine amount for each condition
good_condition_fine = 0
damaged_condition_fine = 5
# calculate the number of days late
days_late = (return_date - datetime.date.today()).days
# calculate the fine amount based on the conditions and the number
of days late
if days_late <= 0:
fine_amount = 0
elif book_condition == 'good':
fine_amount = days_late * good_condition_fine
else:
fine_amount = days_late * damaged_condition_fine
3.2 Calculate and display the monthly salary for two categories of employee
permanent and temporary based on following conditions – count of absent/present,
incentives, etc. Accept month, fixed salary, absent days, incentives (y/n) as input from
user
# take user input for month, fixed salary, absent days, and
incentives
month = input("Enter the month: ")
fixed_salary = float(input("Enter the fixed salary: "))
absent_days = int(input("Enter the number of absent days: "))
incentives = input("Are there any incentives (y/n): ")
def fibonacci_recursive(n):
if n <= 1:
return n
else:
return (fibonacci_recursive(n - 1) + fibonacci_recursive(n -
2))
# arithmetic.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):
return a / b
Save the file and import the module in another Python file. For example:
import arithmetic
a = 10
b = 5
print("Addition of {} and {} is: {}".format(a, b,
arithmetic.add(a, b)))
print("Subtraction of {} and {} is: {}".format(a, b,
arithmetic.subtract(a, b)))
print("Multiplication of {} and {} is: {}".format(a, b,
arithmetic.multiply(a, b)))
print("Division of {} and {} is: {}".format(a, b,
arithmetic.divide(a, b)))
# myfunctions.py
def factorial(num):
if num < 0:
return None
elif num == 0:
return 1
else:
return num * factorial(num - 1)
def primeNumber(num):
if num < 2:
return False
else:
for i in range(2, num):
if num % i == 0:
return False
return True
def powNumber(num, power):
return num ** power
# main.py
import myfunctions
while True:
print("\nSelect an option:")
print("1. Factorial of a number")
print("2. Check if a number is prime or not")
print("3. Power of a number")
print("4. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
num = int(input("Enter a number: "))
print("Factorial of {} is {}".format(num,
myfunctions.factorial(num)))
elif choice == 2:
num = int(input("Enter a number: "))
if myfunctions.primeNumber(num):
print("{} is a prime number".format(num))
else:
print("{} is not a prime number".format(num))
elif choice == 3:
num = int(input("Enter a number: "))
power = int(input("Enter the power: "))
print("{} raised to the power {} is {}".format(num, power,
myfunctions.powNumber(num, power)))
elif choice == 4:
print("Exiting...")
break
else:
print("Invalid choice!")
4.3 Write a program to demonstrate EH in python for handling two exceptions,
namely, IndexError: list index out of range and ZeroDivisionError
class NegativeNumberError(Exception):
pass
def square_root(x):
if x < 0:
raise NegativeNumberError("Cannot take square root of a negative number")
return x**0.5
# Main program
try:
num = int(input("Enter a number: "))
result = square_root(num)
print("The square root of {} is: {}".format(num, result))
except NegativeNumberError as e:
print("Error:", e)
5.2 Create two objects distance1 and distance2 for a class called DISTANCE,
Accept values of distance1 and distance2 from the user in the form of feet and inches
and finally calculate and display the sum of two distances in feet and inches (passing an
object and returning an object to/from a function).
class Distance:
def __init__(self, feet=0, inches=0):
self.feet = feet
self.inches = inches
def display(self):
print("Distance: {} feet, {} inches".format(self.feet,
self.inches))
def get_distance():
feet = int(input("Enter feet: "))
inches = int(input("Enter inches: "))
return Distance(feet, inches)
distance1 = get_distance()
distance2 = get_distance()
distance3 = distance1.add(distance2)
print("Distance 1:")
distance1.display()
print("Distance 2:")
distance2.display()
print("Total distance:")
distance3.display()
5.3 Write a program to implement method overriding
class Animal:
def move(self):
print("Animals can move")
class Dog(Animal):
def move(self):
print("Dogs can walk and run")
class Fish(Animal):
def move(self):
print("Fish can swim")
# create objects
a = Animal()
d = Dog()
f = Fish()
# call the methods
a.move()
d.move()
f.move()
class Bulldog(Dog):
def __init__(self, name, breed, weight):
super().__init__(name, breed)
self.weight = weight
def run(self):
print(self.name, "is running")
# create object
b = Bulldog("Rocky", "Bulldog", 25)
# call methods
b.eat()
b.bark()
b.run()