Program 1 To 17
Program 1 To 17
Write a program that implements a user defined function that accepts Principal Amount, Rate, Time,
Number of Times the interest is compounded to calculate and displays compound interest.
Hint: CI = 𝑃 ∗ 1 + − 𝑃
def calculate_compound_interest(principal, rate, time, n):
amount = principal * (1 + rate / n) ** (n * time)
compound_interest = amount - principal
print("The compound interest is:", compound_interest)
def main():
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the annual interest rate (in percentage): ")) / 100
time = float(input("Enter the time (in years): "))
n = int(input("Enter the number of times interest is compounded per year: "))
calculate_compound_interest(principal, rate, time, n)
if __name__ == "__main__":
main()
2. Write a program that has a user defined function to accept 2 numbers as parameters, if number 1 is less
than number 2 then numbers are swapped and returned, i.e., number 2 is returned in place of number1 and
number 1 is reformed in place of number 2, otherwise the same order is returned.
def swap(num1, num2):
if num1 < num2:
return num2, num1
else:
return num1, num2
def main():
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result1, result2 = swap(num1, num2)
print(“After processing:”,result1, result2)
if __name__ == "__main__":
main()
3. Write a program that contains user defined functions to calculate area, perimeter or surface area whichever
is applicable for various shapes like square, rectangle, triangle, circle and cylinder. The user defined
functions should accept the values for calculation as parameters and the calculated value should be
returned. Import the module and use the appropriate functions.
import math
def square():
length=float(input("Enter Side of Square"))
print("Area of Square is: ",length*length)
print("Perimeter of Square is: ",4*length)
def rectangle():
length=float(input("Enter Length: "))
bredth=float(input("Enter Bredth: "))
print("Area of Square is: ",length*bredth)
print("Perimeter of Square is: ",2(length+bredth))
def triangle():
side1=float(input("Enter Side1: "))
side2=float(input("Enter Side2: "))
side3=float(input("Enter Side3: "))
s=(side1+side2+side3)/2
area=math.sqrt(s*(s-side1)(s-side2)(s-side3))
print("Area of Triangle is: ",area)
def circle():
radius=float(input("Enter Radius"))
area=3.14*radius*radius
circumference=2*3.14*radius
print("Area of Circle is: ",area)
print("Circumference of Circle is: ",circumference)
def cylinder():
radius=float(input("Enter Radius"))
height=float(input("Enter Height"))
area=3.14*radius*radius*height
surfacearea=2*3.14*radius*(height+radius)
print("Area of Cylinder is: ",area)
print("surface Area of Cylinder is:",surfacearea)
print('''Options are
1. Square
2. Rectangle
3. Triangle
4. Circle
5. Cylinder
''')
ch=int(input("Enter Uour Option"))
if ch==1:
square()
elif ch==2:
rectangle()
elif ch==3:
triangle()
elif ch==4:
circle()
elif ch==5:
cylinder()
else:
print("Wrong Input")
4. Write a program using function to accept a string and print the number of uppercase, lowercase, vowels,
consonants and spaces.
def program4(string):
uppercase=0
lowercase=0
vowels=0
consonants=0
spaces=0
for i in range(len(string)):
if string[i].isupper():
uppercase+=1
if string[i].islower():
lowercase+=1
if (string[i] in ("a","A","e","E","i","I","o","O","U","u")):
vowels+=1
if (string[i] not in ("a","A","e","E","i","I","o","O","U","u")):
consonants+=1
if string[i]==" ":
spaces+=1
6. Write a python program to accept username “Admin” as default argument and password 123 entered by
user to allow login into the system.
def user_pass(password, username= “Admin”):
if password == ‘123’:
print(“You have Logged into System”)
else:
print(“Password is Incorrect!!!!!”)
password=input(“Enter Password: ”)
user_password(password)
7. Write a random number generator that generates random numbers between 1 and 6 (simulates a dice)
import random
while True:
print("="*55)
print(" **************** ROLLING THE DICE****************”)
print("="*55)
num=random.randint (1,6)
if num==6:
print("Hey..... You got", num, "....Congratulations!!!")
elif num==1:
print("Well tried..... But you got ", num)
else:
print("You got: ", num)
ch=input("Roll again? (Y/N)")
if ch in 'Nn':
break
print("Thanks for Playing !!!!!!!!!")
8. Write a Python program to accept a list as a function parameter and raise the IndexError exception.
def raise_index_error(lst):
try:
idx=int(input("Enter list index to access the value"))
print(lst[idx])
except IndexError:
print("Index not found in the list")
def main():
l=eval(input("Enter the list:"))
raise_index_error(l)
main()
9. Create a text file "intro.txt" in python and ask the user to write a single line text by user input.
def program():
f = open("intro.txt","w")
text=input("Enter the text:")
f.write(text)
f.close()
program()
10. Suppose there is a file in which some content is written, write a program which counts all the line
and ask the user which specific line he wants to read
with open ("Text.txt", 'r') as f:
length=len (f.readlines ())
print (“Total Number of Lines present in the file are: ”, length)
n=int (input ("Enter Line which you want to read"))
if n>0 and n<=length:
f.seek(0)
a=f.readlines ()
print (a [n-1])
else:
print ("Invalid Input")
11. Read a text file line by line and display each word separated by a #.
File content:
I love programming
Python is amazing
def display_words_with_hash():
try:
with open('input.txt', 'r') as file:
for line in file:
words = line.split()
print(output)
except FileNotFoundError:
print("The file 'input.txt' was not found.")
12. Write a Python program to implement a stack using list.
stack = []
# Define the stack operations OUTPUT
def push(item):
stack.append(item)
print("Item " + item + " pushed to stack.")
def pop():
if is_empty():
print("Stack is empty!")
else:
item = stack.pop()
print("Item " + item + " popped from stack.")
def peek():
if is_empty():
print("Stack is empty!")
else:
print("Top item is: " + stack[-1])
def is_empty():
return len(stack) == 0
def size():
print("Stack size is: " + str(len(stack)))
try:
choice = int(input("Enter choice (1-6): "))
except ValueError:
print("Invalid input! Please enter a number between 1 and 6.")
continue
if choice == 1:
item = input("Enter item to push: ")
push(item)
elif choice == 2:
pop()
elif choice == 3:
peek()
elif choice == 4:
if is_empty():
print("Stack is empty.")
else:
print("Stack is not empty.")
elif choice == 5:
size()
elif choice == 6:
print("Exiting...")
break
else:
print("Invalid choice! Please select a number between 1 and 6.")
if __name__ == "__main__":
stack_operations()
13. Create a CSV file by entering user-id and password, read and search the password for given userid.
import csv
def create_csv():
writer.writerow([user_id, password])
print("User ID and password saved to CSV file.")
def search_password():
user_id_to_search = input("Enter the User ID to search for: ")
def main():
while True:
print("\n1. Create User ID and Password")
print("2. Search Password by User ID")
print("3. Exit")
try:
choice = int(input("Enter your choice (1-3): "))
except ValueError:
print("Invalid choice! Please enter a number between 1 and 3.")
continue
if choice == 1:
create_csv()
elif choice == 2:
search_password()
elif choice == 3:
print("Exiting...")
break
else:
print("Invalid choice! Please select a number between 1 and 3.")
if __name__ == "__main__":
main()
OUTPUT
14.
15
16. Consider the following MOVIE table and write the SQL queries based on it.