0% found this document useful (0 votes)
104 views19 pages

Untitled

The document contains Python programs to demonstrate basic programming concepts like data types, operators, control flow, functions, and modules. It includes programs to: 1) Display odd and even numbers in a range, reverse a number, print Fibonacci series, and numbers divisible by 4 and 7. 2) Demonstrate list operations like counting data types, searching, sorting, and list comprehensions. 3) Calculate library fine and employee salary using functions. The salary program accepts user input and contains separate functions for permanent and temporary employees. 4) Show creating a user-defined module containing arithmetic functions and handling exceptions.

Uploaded by

Amaan Jambura
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views19 pages

Untitled

The document contains Python programs to demonstrate basic programming concepts like data types, operators, control flow, functions, and modules. It includes programs to: 1) Display odd and even numbers in a range, reverse a number, print Fibonacci series, and numbers divisible by 4 and 7. 2) Demonstrate list operations like counting data types, searching, sorting, and list comprehensions. 3) Calculate library fine and employee salary using functions. The salary program accepts user input and contains separate functions for permanent and temporary employees. 4) Show creating a user-defined module containing arithmetic functions and handling exceptions.

Uploaded by

Amaan Jambura
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

[1].

Basic Programming Elements (Data types, print(), input(), operators, if-else,


looping,...)
Write Python programs to
1.1 Display odd and even numbers between a given range

# Python program to display odd and even numbers between a given


range
start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))
print("Even numbers between", start, "and", end, "are: ")
for num in range(start, end+1):
if num % 2 == 0:
print(num, end=" ")
print("\nOdd numbers between", start, "and", end, "are: ")
for num in range(start, end+1):
if num % 2 != 0:
print(num, end=" ")

1.2 Print an n digit number in reverse order

num = int(input("Enter an n-digit number: "))

# convert the number to a string and reverse it using slicing


reverse_num = str(num)[::-1]

print("The reverse of", num, "is:", reverse_num)

1.3 Print Fibonacci series up to n members


n = int(input("Enter the number of terms: "))

# initialize the first two terms


a, b = 0, 1

# check if the number of terms is valid


if n <= 0:
print("Please enter a positive integer")
elif n == 1:
print("Fibonacci sequence up to", n, "term:")
print(a)
else:
print("Fibonacci sequence up to", n, "terms:")
# print the first two terms
print(a, b, end=" ")
# generate and print the next terms
for i in range(2, n):
c = a + b
print(c, end=" ")
a, b = b, c

1.4 Print all the numbers between 100 to 200 which are divisible by 4 and 7

print("Numbers between 100 to 200 which are divisible by 4 and


7:")
for num in range(100, 201):
if num % 4 == 0 and num % 7 == 0:
print(num, end=" ")

1.5 Display a number pattern using nested looping

n = int(input("Enter the number of rows: "))

for i in range(1, n+1):


for j in range(1, i+1):
print(j, end=" ")
print()

[2] Python - LIST


Write Python program to....
2.1 Display the count of list elements of different data types.

my_list = [1, "hello", 3.5, "world", 5, True, None]


# initialize the counters for each data type
int_count = 0
float_count = 0
str_count = 0
bool_count = 0
none_count = 0
# loop through the list and count the elements of each data type
for element in my_list:
if isinstance(element, int):
int_count += 1
elif isinstance(element, float):
float_count += 1
elif isinstance(element, str):
str_count += 1
elif isinstance(element, bool):
bool_count += 1
elif element is None:
none_count += 1
# print the counts of each data type
print("Count of different data types in the list:")
print("Integers:", int_count)
print("Floats:", float_count)
print("Strings:", str_count)
print("Booleans:", bool_count)
print("None:", none_count)

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

2.4 Demonstrate list comprehensions using an example.


# create a list of numbers from 1 to 10
numbers = [x for x in range(1, 11)]
# create a new list with squares of the numbers
squares = [x**2 for x in numbers]
# create a new list with even numbers from the original list
even_numbers = [x for x in numbers if x % 2 == 0]
# create a new list with odd numbers from the original list
odd_numbers = [x for x in numbers if x % 2 != 0]
# print the original list and the new lists
print("Original list:", numbers)
print("Squares of the numbers:", squares)
print("Even numbers from the list:", even_numbers)
print("Odd numbers from the list:", odd_numbers)

2.5 Display the name of the month from a given date

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

# print the fine amount


print("Fine amount:", fine_amount)

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

# function to calculate monthly salary for permanent employees


def calculate_permanent_salary(fixed_salary, absent_days,
incentives):
basic_salary = fixed_salary / 12
deduction = absent_days * (basic_salary / 30)
if incentives == 'y':
total_salary = fixed_salary / 12 + (fixed_salary / 12) * 0.1
- deduction
else:
total_salary = fixed_salary / 12 - deduction
return total_salary

# function to calculate monthly salary for temporary employees


def calculate_temporary_salary(fixed_salary, absent_days,
incentives):
basic_salary = fixed_salary / 12
deduction = absent_days * (basic_salary / 30)
if incentives == 'y':
total_salary = fixed_salary / 12 + (fixed_salary / 12) *
0.05 - deduction
else:
total_salary = fixed_salary / 12 - deduction
return total_salary

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

# calculate and display the monthly salary for permanent and


temporary employees
permanent_salary = calculate_permanent_salary(fixed_salary,
absent_days, incentives)
temporary_salary = calculate_temporary_salary(fixed_salary,
absent_days, incentives)

print("\nMonthly Salary Report for the month of", month)


print("--------------------------------------------------")
print("Permanent Employee Salary:", permanent_salary)
print("Temporary Employee Salary:", temporary_salary)
3.3 Display Fibonacci series elements using recursive method

def fibonacci_recursive(n):
if n <= 1:
return n
else:
return (fibonacci_recursive(n - 1) + fibonacci_recursive(n -
2))

# take user input for the number of terms in the series


n_terms = int(input("Enter the number of terms in the Fibonacci
series: "))

# display the Fibonacci series using recursive method


print("Fibonacci Series:")
for i in range(n_terms):
print(fibonacci_recursive(i), end=" ")

[4] Python – User defined modules and exception handling


4.1 Write a program to demonstrate the steps involved in creating user defined
modules(Arithmetic operations)
 Create a new Python file called arithmetic.py.
 Define the arithmetic operations functions in this file. For example:

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

 Run the main.py file to see the output:

4.2 Create a module having 3 functions – factorial(), primeNumber() and


powNumber(). In an another program import this module to access all the functions
(menu driven program).

# 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

def divide_numbers(a, b):


try:
result = a / b
except ZeroDivisionError:
print("Error: Division by zero!")
return None
else:
print("The result of division is:", result)
return result
def get_list_element(my_list, index):
try:
result = my_list[index]
except IndexError:
print("Error: Index out of range!")
return None
else:
print("The element at index {} is: {}".format(index,
result))
return result
# Main program
a = 10
b = 0
result = divide_numbers(a, b)
print()
my_list = [1, 2, 3, 4, 5]
index = 10
element = get_list_element(my_list, index)
4.4 Write a program to RAISE and handle user defined exception

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] Python – OOPs


5.1 Write an object oriented program to demonstrate working of default and
parameterized constructors.
class Person:
def __init__(self, name="", age=0):
self.name = name
self.age = age
def display(self):
print("Name:", self.name)
print("Age:", self.age)
# Using default constructor
p1 = Person()
p1.display()
# Using parameterized constructor
p2 = Person("John", 30)
p2.display()

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 add(self, d2):


feet = self.feet + d2.feet
inches = self.inches + d2.inches
if inches >= 12:
feet += 1
inches -= 12
return Distance(feet, 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()

5.4 Write a program to implement multilevel inheritance (use of super())


class Animal:
def __init__(self, name):
self.name = name
def eat(self):
print(self.name, "is eating")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def bark(self):
print(self.name, "is barking")

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

You might also like