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

Program 1 To 17

The document contains multiple Python programming tasks, including functions for calculating compound interest, swapping numbers, calculating areas and perimeters of shapes, analyzing strings, managing user login, generating random numbers, handling lists and files, implementing a stack, and creating a CSV file for user data. Each task is accompanied by sample code demonstrating the required functionality. Additionally, there are SQL queries related to movie and patient tables, showcasing data retrieval and manipulation.

Uploaded by

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

Program 1 To 17

The document contains multiple Python programming tasks, including functions for calculating compound interest, swapping numbers, calculating areas and perimeters of shapes, analyzing strings, managing user login, generating random numbers, handling lists and files, implementing a stack, and creating a CSV file for user data. Each task is accompanied by sample code demonstrating the required functionality. Additionally, there are SQL queries related to movie and patient tables, showcasing data retrieval and manipulation.

Uploaded by

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

1.

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

print("Total Uppercase Letters are: ",uppercase)


print("Total Lowercase Letters are: ",lowercase)
print("Total Vowels are: ",vowels)
print("Total Consonants are: ",consonants)
print("Total Spaces are: ",spaces)

value=input("Enter Your String: ")


program4(value)
5. Example of Global and Local variables in function
x=“global”
def display():
global x
y = “local”
x = x * 2
print(x)
print(y)
display()

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

# Join the words with a '#' separator


output = '#'.join(words)

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

# Function to handle user input (switch-case-like approach)


def stack_operations():
while True:
print("\nChoose an operation:")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Check if stack is empty")
print("5. Stack size")
print("6. Exit")

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

with open('user_data.csv', mode='a', newline='') as file:


writer = csv.writer(file)

user_id = input("Enter User ID: ")


password = input("Enter Password: ")

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

with open('user_data.csv', mode='r') as file:


reader = csv.reader(file)

for row in reader:


user_id = row[0]
password = row[1]
if user_id == user_id_to_search:
print("Password for User ID '" + user_id + "': " + password)
return

print("User ID '" + user_id_to_search + "' not found.")

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.

a. Display all information from movie.


b. Display the type of movies.
c. Display movieid, moviename, total_eraning by showing the business done by the movies. Claculate
the business done by movie using the sum of productioncost and businesscost.
d. Display movieid, moviename and productioncost for all movies with productioncost greater thatn
150000 and less than 1000000.
e. Display the movie of type action and romance.
f. Display the list of movies which are going to release in February, 2022.
Answers.
a. select * from movie;
b. select distinct from a movie;

c. select movieid, moviename, productioncost + businesscost "total earning" from movie;


d. select movie_id,moviename, productioncost from movie where producst is >150000 and <1000000;

e. select moviename from movie where type ='action' or type='romance';

f. select moviename from movie where month(releasedate)=2;


17. Consider the given table patient and Write following queries:

a. Display the total charges of patient admitted in the month of November.


b. Display the eldest patient with name and age.
c. Count the unique departments.
d. Display an average charges.
Answers:
a. select sum(charges) from patient where dateofadm like '%-11-%';
b. select pname,max(age) from patient;

c. Select count(distinct department) from patient;

d. Select avg(charges) from patient;

You might also like