Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

1. WAP to show functionality of a basic calculator using functions.

Ans)
# WAP to show functionality of a basic calculator using functions.
#Made by Nishant

# program to add
def add(x, y):
return x + y

# program to subtract
def subtract(x, y):
return x - y

# program to multiply
def multiply(x, y):
return x * y

# program to divide
def divide(x, y):
return x / y

# printing parts
print("Select Operations")
print("Press 1 - Add No.s")
print("Press 2 - Subtract No.s")
print("Press 3 - Multiply No.s")
print("Press 4 - Divide No.s")
print("Press 5 - Continue")
# Programing Parts
while True:
ch = int(input("Choose operation 1/2/3/4/5: "))
# Selection The Program
if ch == 1:
num1 = float(input("Enter First No.: "))
num2 = float(input("Enter Second No.: "))
print(num1, '+', num2, '=', add(num1, num2))
elif ch == 2:
num1 = float(input("Enter First No.: "))
num2 = float(input("Enter Second No.: "))
print(num1, '-', num2, '=', subtract(num1, num2))
elif ch == 3:
num1 = float(input("Enter First No.: "))
num2 = float(input("Enter Second No.: "))
print(num1, '*', num2, '=', multiply(num1, num2))
elif ch == 4:
num1 = float(input("Enter First No.: "))
num2 = float(input("Enter Second No.: "))
print(num1, '/', num2, '=', divide(num1, num2))
elif ch == 5:
ans = input("Do You Want To End Calculator (Y/N): ")
if ans.upper() == 'Y':
break
OUTPUT
2. WAP USING a function in python which accept a number from user to return True, if the
number is a prime number else return False. Use this function to print all prime
numbers from 1 to 100.

Ans) # WAP USING a function in python which accept a number from user to
return True,
# if the number is a prime number else return False.
# Use this function to print all prime numbers from 1
# Made By Nishant
num = int(input("Enter a number: "))
# If given number is greater than 1 and less then 100
if 1 < num < 100:
# Iterate from 2 to n / 2
for i in range(2, int(num / 2) + 1):
# If num is divisible by any number between
# 2 and n / 2, it is not prime
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
OUTPUT
3. WAP USING a function in python which accept a list of marks of students and return the

minimum mark, maximum mark and the average marks.

Ans) # Python Program to find Total, Average, and Percentage of Five Subjects
# Made By Nishant
l = []
while True:
# Student's Details Program
name = input("Enter Name Of Student: ")
Class = int(input("Enter Class: "))
roll = int(input("Enter Roll no.: "))
# Adding Marks
english = float(input("Please enter English Marks: "))
math = float(input("Please enter Math score: "))
computers = float(input("Please enter Computer Marks: "))
physics = float(input("Please enter Physics Marks: "))
chemistry = float(input("Please enter Chemistry Marks: "))
# Creating A List and Add marks and and divide by 5 for average marks
data = [name, Class, roll, english, math, computers, physics, chemistry]
total = english + math + computers + physics + chemistry
average = total / 5
percentage = (total / 500) * 100
# printing section
print("\nTotal Marks = %.2f" % total)
print("Average Marks = %.2f" % average)
print("Marks Percentage = %.2f" % percentage)
# adding more or not
ans = input("Do You Want To add more (Y/N): ")
if ans.upper() == 'N':
break
OUTPUT
4. WAP to read a text file “myfile.txt” line by line and display each word separated by a #.

Ans) # WAP to read a text file “myfile.txt” line by line and display each
word separated by a #.
# Made By Nishant
fh = open(r"myfile.txt", "r")
item = []
a = ""
while True:

a = fh.readline()

words = a.split()
for j in words:
item.append(j)
if a == "":
break
print("\t\n#".join(item))
OUTPUT
5. WAP to read a text file “myfile.txt” and display the number of vowels/ consonants/

uppercase/ lowercase characters in the file.

Ans) # WAP to read a text file “myfile.txt” and display the number of vowels/
consonants/
# uppercase/ lowercase characters in the file.
# Made By Nishant

# Opening the file in read mode


f = open("myfile.txt", "r")

# Initialize four variables to count number of vowels,


# consonants, Uppercase and Lowercase respectively
vowel = 0
consonants = 0
uppercase = 0
lowercase = 0

# Make a vowels list so that we can


# check whether the character is vowel or not
vowels_list = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
consonants_list = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n',
'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y',
'z']
uppercase_list = ['A', 'B', 'C', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z']
lowercase_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z']

# Iterate over the characters present in file


for i in f.read():

# Checking if the current character is vowel or not


if i in vowels_list:
vowel += 1

# Checking if the current character is consonant or not


elif i in consonants_list:
consonants += 1

# Checking if the current character is uppercase or not


elif i in uppercase_list:
uppercase += 1

# Checking if the current character is lowercase or not


elif i in lowercase_list:
lowercase += 1

# Print the desired output on the console.


print("Number of vowels in ", " = ", vowel)
print("Number of consonants in ", " = ", consonants)
print("Number of uppercase in ", " = ", uppercase)
print("Number of lowercase in ", " = ", lowercase)
OUTPUT
6. Remove all the lines that contain the character `a' in a file and write it to another file.

Ans) # Remove all the lines that contain the character `a' in a file and
write it to another file.
# Made By Nishant
# Create a New File and write something.
fo=open("hp.txt","w")
fo.write("Harry Potter\n")
fo.write("There is a difference in all harry potter books\nWe can see it as
harry grows\nthe books were written by J.K rowling ")
fo.close()

fo=open('hp.txt','r')
fi=open('writehp.txt','w')
l=fo.readlines()
for i in l:
if 'a' in i:
i=i.replace('a','')
fi.write(i)
fi.close()
fo.close()
OUTPUT
7. Write a program to create a text file and print the lines starting with ‘T’ or ‘P’. (Both

uppercase and lowercase).

Ans) # Write a program to create a text file and print the lines starting
with ‘T’ or ‘P’. (Both uppercase and lowercase).
# Made by Nishant
# Read Any Text File And Make New File For Print
fin = open("myfile.txt", "r")
fout = open("story.txt", "w")
# Read All Lines
s = fin.readlines()
# Programing Area
for i in s:
if 'p' in i:
fout.write(i)
fin.close()
fout.close()
8. Read a text file to print the frequency of the word ‘He’ and ‘She’ found in the file.

Ans) f = open("heshe.txt","r")
count = 0
county = 0
t = f.read()
p = t.split()
for i in p:
if i == "he":
count = count + 1
elif i == "she":
county = county + 1
print("Frequency of 'he' is: ", count)
print("Frequency of 'she' is: ", county)
OUTPUT
9. Create a binary file with name and roll number. Search for a given roll number and

display the name, if not found display appropriate message.

Ans) # Create a binary file with name and roll number. Search for a given
roll number and
# display the name, if not found display appropriate message.
import pickle

# creating the file and writing the data


f = open("records.dat", "wb")
# list index 0 = roll number
# list index 1 = name
# list index 2 = marks
pickle.dump([1, "Wakil", 90], f)
pickle.dump([2, "Tanish", 80], f)
pickle.dump([3, "Priyashi", 90], f)
pickle.dump([4, "Kanupriya", 80], f)
pickle.dump([5, "Ashutosh", 85], f)
f.close()

# opeining the file to read contents


f = open("records.dat", "rb")
roll = int(input("Enter the Roll Number: "))
marks = float(input("Enter the updated marks: "))
List = [] # empty list
flag = False # turns to True if record is found
while True:
try:
record = pickle.load(f)
List.append(record)
except EOFError:
break
f.close()

# reopening the file to update the marks


f = open("records.dat", "wb")
for rec in List:
if rec[0] == roll:
rec[2] = marks
pickle.dump(rec, f)
print("Record updated successfully")
flag = True
else:
pickle.dump(rec, f)
f.close()
if not flag:
print("This roll number does not exist")
OUTPUT
10. Create a binary file with roll number, name and marks. Input a roll number and update

the marks.

Ans) import pickle


student_data = {}
# writing to the file- logic
no_of_students = int(input("Enter no of students "))
file = open("stud_u.dat", "wb")
for i in range(no_of_students):
student_data["RollNo"] = int(input("Enter roll no "))
student_data["Name"] = input("Enter student Name: ")
student_data["Marks"] = float(input("Enter student marks: "))
pickle.dump(student_data, file)
student_data = {}
file.close()
# reading the file- logic
file = open("stud_u.dat", "rb")
try:
while True:
student_data = pickle.load(file)
print(student_data)
except EOFError:
file.close()
# searching and updating (i.e. reading and then writing) logic
found = False
roll_no = int(input("Enter the roll no to search: "))
file = open("stud_u.dat", "rb+")
try:
while True:
pos = file.tell()
student_data = pickle.load(file)
if (student_data["RollNo"] == roll_no):
# print (student_data["Name"])
student_data["Marks"] = float(input("Enter marks to be updated"))
file.seek(pos)
pickle.dump(student_data, file)
found = True
except EOFError:
if (found == False):
print("Roll no not found please try again")
else:
print("Student marks updated successfully. ")
file.close()
# Prepared by RKS
# Displaying logic
file = open("stud_u.dat", "rb")
try:
while True:
student_data = pickle.load(file)
print(student_data)
except EOFError:
file.close()
OUTPUT
11. Read a CSV file from hard disc and print all the details on the screen.

Ans) import csv


with open('people.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)

12. Read a CSV file (containing item no, name, rate, QOH) from hard disc and print all the

items whose rate is between Rs 500 and Rs 1000.

13. Create a CSV file by entering user-id and password, read and search the password for

given userid.

Ans) # Create a CSV file by entering user-id and password, read and search
the password for given userid.
import csv

with open("user_info.csv", "w") as obj:


fileobj = csv.writer(obj)
fileobj.writerow(["User Id", "password"])
while True:
user_id = input("enter id: ")
password = input("enter password: ")
record = [user_id, password]
fileobj.writerow(record)
x = input("press Y/y to continue and N/n to terminate the program: ")
if x.lower() == "n":
break
with open("user_info.csv", "r") as obj2:
fileobj2 = csv.reader(obj2)
given = input("enter the user id to be searched\n")
for i in fileobj2:
next(fileobj2)
# print(i,given)
if i[0] == given:
print(i[1])
break
OUTPUT
14. Write a random number generator that generates random numbers between 1 and 6

(simulates a dice). Throw the two dices for 10 times and print their total.

Ans) # Write a random number generator that generates random numbers between
1 and 6 (simulates a dice). Throw the two dices for 10 times and print their
total.
import random

min1 = 1
max2 = 6
roll_again = "y"
while roll_again.upper() == "Y":
print("Rolling the dice...")
val = random.randint(min1, max2)
print("You get... :", val)
roll_again = input("Roll the dice again? (y/n)...")

OUTPUT
15. WAP in Python to demonstrate linear search.

Ans) def search(arr, curr_index, key):


if curr_index == -1:
return -1
if arr[curr_index] == key:
return curr_index
return search(arr, curr_index - 1, key)

16. Write a Python program to implement a stack using a list data-structure.

17. WAP to pass an integer list as stack to a function and push only those elements in the

stack which are divisible by 7.

Ans) def PUSH(Arr,value):


s=[]
for x in range(0,len(Arr)):
if Arr[x]%5==0:
s.append(Arr[x])
if len(s)==0:
print("Empty Stack")
else:
print(s)

You might also like