0% found this document useful (0 votes)
14 views21 pages

Wa0003.

The document contains a series of Python programming tasks that demonstrate various functionalities, including checking for prime numbers, palindrome detection, finding the largest and smallest numbers in a list, tuple swapping, and managing student records in a dictionary. It also includes file handling operations such as reading and writing files, counting characters, and manipulating file content. Each task is accompanied by code snippets and sample outputs, showcasing the implementation of the described functionalities.

Uploaded by

r3436210
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)
14 views21 pages

Wa0003.

The document contains a series of Python programming tasks that demonstrate various functionalities, including checking for prime numbers, palindrome detection, finding the largest and smallest numbers in a list, tuple swapping, and managing student records in a dictionary. It also includes file handling operations such as reading and writing files, counting characters, and manipulating file content. Each task is accompanied by code snippets and sample outputs, showcasing the implementation of the described functionalities.

Uploaded by

r3436210
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/ 21

1.Write a Program to show whether entered numbers are prime or not in the given range.

lower=int(input("Enter lowest number as lower bound to check : "))


upper=int(input("Enter highest number as upper bound to check: "))
c=0
for i in range(lower, upper+1):
if (i == 1):
continue

# flag variable to tell if i is prime or not


flag = 1

for j in range(2, i // 2 + 1):


if (i % j == 0):
flag = 0
break

# flag = 1 means i is prime


# and flag = 0 means i is not prime
if (flag == 1):
print(i, end = " ")

Output:

===== RESTART: C:/Users/HP/AppData/Local/Programs/Python/Python313/ex-1.py =====

Enter lowest number as lower bound to check : 2

Enter highest number as upper bound to check: 9

2357

2. Input a string and determine whether it is a palindrome or not.

string=input('Enter a string:')
length=len(string)
mid=length//2
rev=-1
for a in range(mid):
if string[a]==string[rev]:
print(string,'is a palindrome.')
break
else:
print(string,'is not a palindrome.')

Output:

===== RESTART: C:/Users/HP/AppData/Local/Programs/Python/Python313/ex-1.py =====

Enter a string:DAV Public School

DAV Public School is not a palindrome.

DAV Public School is not a palindrome.


DAV Public School is not a palindrome.

DAV Public School is not a palindrome.

DAV Public School is not a palindrome.

DAV Public School is not a palindrome.

DAV Public School is not a palindrome.

DAV Public School is a palindrome.

3. Find the largest/smallest number in a list/tuple

# creating empty list


list1 = []

# asking number of elements to put in list


num = int(input("Enter number of elements in list: "))

# iterating till num to append elements in list


for i in range(1, num + 1):
ele= int(input("Enter elements: "))
list1.append(ele)

# print maximum element


print("Largest element is:", max(list1))

# print minimum element


print("Smallest element is:", min(list1))

Output:
===== RESTART: C:/Users/HP/AppData/Local/Programs/Python/Python313/ex-1.py =====

Enter number of elements in list: 5

Enter elements: 34

Enter elements: 45

Enter elements: 76

Enter elements: 77

Enter elements: 76

Largest element is: 77

Smallest element is: 34

4. WAP to input any two tuples and swap their values.

t1 = tuple()
n = int (input("Total no of values in First tuple: "))
for i in range(n):
a = input("Enter Elements : ")
t1 = t1 + (a,)
t2 = tuple()
m = int (input("Total no of values in Second tuple: "))
for i in range(m):
a = input("Enter Elements : ")
t2 = t2 + (a,)
print("First Tuple : ")
print(t1)
print("Second Tuple : ")
print(t2)

t1,t2 = t2, t1

print("After Swapping: ")


print("First Tuple : ")
print(t1)
print("Second Tuple : ")
print(t2)

Output:

===== RESTART: C:/Users/HP/AppData/Local/Programs/Python/Python313/ex-1.py =====

Total no of values in First tuple: 5

Enter Elements : 56

Enter Elements : 55

Enter Elements : 77

Enter Elements : 45

Enter Elements : 87

Total no of values in Second tuple: 3

Enter Elements : 23

Enter Elements : 98

Enter Elements : 66

First Tuple :

('56', '55', '77', '45', '87')

Second Tuple :

('23', '98', '66')

After Swapping:

First Tuple :

('23', '98', '66')

Second Tuple :
('56', '55', '77', '45', '87')

5. WAP to store students’ details like admission number, roll number, name and percentage in a
dictionary and display information on the basis of admission number.

record = dict ()
i=1
n= int (input ("How many records u want to enter: "))
while(i<=n):
Adm = input("Enter Admission number: ")
roll = input("Enter Roll Number: ")
name = input("Enter Name :")
perc = float(input("Enter Percentage : "))
t = (roll,name, perc)
record[Adm] = t
i=i+1
Nkey = record.keys()
for i in Nkey:
print("\nAdmno- ", i, " :")
r = record[i]
print("Roll No\t", "Name\t", "Percentage\t")
for j in r:
print(j, end = "\t")

Output:

===== RESTART: C:\Users\HP\AppData\Local\Programs\Python\Python313\ex-1.py =====

How many records u want to enter: 3

Enter Admission number: 27357

Enter Roll Number: 33

Enter Name :Suhas panda

Enter Percentage : 92

Enter Admission number: 37827

Enter Roll Number: 26

Enter Name :Dev sharma

Enter Percentage : 93

Enter Admission number: 36376

Enter Roll Number: 11

Enter Name :Aditi roy

Enter Percentage : 87
Admno- 27357 :

Roll No Name Percentage

33 Suhas panda 92.0

Admno- 37827 :

Roll No Name Percentage

26 Dev sharma 93.0

Admno- 36376 :

Roll No Name Percentage

11 Aditi roy 87.0

6. Write a program with a user-defined function with string as a parameter which replaces all vowels
in the string with ‘*’.

def strep(str):

# convert string into list

str_lst =list(str)

# Iterate list

for i in range(len(str_lst)):

# Each Character Check with Vowels

if str_lst[i] in 'aeiouAEIOU':

# Replace ith position vowel with'*'

str_lst[i]='*'

#to join the characters into a new string.

new_str = "".join(str_lst)
return new_str

def main():
line = input("Enter string: ")
print("Orginal String")
print(line)
print("After replacing Vowels with '*'")
print(strep(line))
main()
Output:

===== RESTART: C:\Users\HP\AppData\Local\Programs\Python\Python313\ex-1.py =====

Enter string: hello i am subhashree

Orginal String
hello i am subhashree

After replacing Vowels with '*'

h*ll* * *m s*bh*shr**

7. Recursively find the factorial of a natural number.

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

def main():
n = int(input("Enter any number: "))
print("The factorial of given number is: ",factorial(n))
main()

Output:

===== RESTART: C:\Users\HP\AppData\Local\Programs\Python\Python313\ex-1.py =====

Enter any number: 76

The factorial of given number is:


18854947016660502549879322608611465582303945353793293356724879829618440434955379
23117729972224000000000000000000

8. Write a recursive code to find the sum of all elements of a list.

def lstSum(lst,n):
if n==0:
return 0
else:
return lst[n-1]+lstSum(lst,n-1)

mylst = [] # Empty List

#Loop to input in list

num = int(input("Enter how many number :"))


for i in range(num):
n = int(input("Enter Element "+str(i+1)+":"))
mylst.append(n) #Adding number to list
sum = lstSum(myl
st,len(mylst))
print("Sum of List items ",mylst, " is :",sum)

Output:

===== RESTART: C:\Users\HP\AppData\Local\Programs\Python\Python313\ex-1.py =====

Enter how many number :3


Enter Element 1:23

Enter Element 2:65

Enter Element 3:87

Sum of List items [23, 65, 87] is : 175

9. Write a recursive code to compute the nth Fibonacci number.

def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return(fibonacci(n-2) + fibonacci(n-1))

nterms = int(input("Please enter the Range Number: "))

# check if the number of terms is valid


if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(fibonacci(i),end=' ')

Output:

===== RESTART: C:\Users\HP\AppData\Local\Programs\Python\Python313\ex-1.py =====

Please enter the Range Number: 5

Fibonacci sequence:

0 1 1 2 3

10.Read a text file line by line and display each word separated by a #.

filein = open("Mydoc.txt",'r')
line =" "
while line:
line = filein.readline()
#print(line)
for w in line:
if w == ' ':
print('#',end = '')
else:
print(w,end = '')
filein.close()
'''
#-------------OR------------------

filein = open("Mydoc.txt",'r')
for line in filein:
word= line .split()
for w in word:
print(w + '#',end ='')
print()
filein.close()

'''

Output:

===== RESTART: C:\Users\HP\AppData\Local\Programs\Python\Python313\ex-1.py =====

i#am#reading#in#DAV#Public#School

11. Read a text file and display the number of vowels/ consonants/ uppercase/ lowercase characters
and other than character and digit in the file.

filein = open("Mydoc1.txt",'r')
line = filein.read()
count_vow = 0
count_con = 0
count_low = 0
count_up = 0
count_digit = 0
count_other = 0
print(line)
for ch in line:
if ch.isupper():
count_up +=1
if ch.islower():
count_low += 1
if ch in 'aeiouAEIOU':
count_vow += 1
if ch.isalpha():
count_con += 1
if ch.isdigit():
count_digit += 1
if not ch.isalnum() and ch !=' ' and ch !='\n':
count_other += 1

print("Digits",count_digit)
print("Vowels: ",count_vow)
print("Consonants: ",count_con-count_vow)
print("Upper Case: ",count_up)
print("Lower Case: ",count_low)
print("other than letters and digit: ",count_other)

filein.close()

Output:

===== RESTART: C:\Users\HP\AppData\Local\Programs\Python\Python313\ex-1.py =====

hello this is subhashree pradhan

Digits 0

Vowels: 10

Consonants: 18

Upper Case: 0

Lower Case: 28

other than letters and digit: 0

12. Write a Python code to find the size of the file in bytes, the number of lines, number of words
and no. of character.

import os

lines = 0
words = 0
letters = 0
filesize = 0

for line in open("Mydoc.txt"):


lines += 1
letters += len(line)
# get the size of file
filesize = os.path.getsize("Mydoc.txt")

# A flag that signals the location outside the word.


pos = 'out'
for letter in line:
if letter != ' ' and pos == 'out':
words += 1
pos = 'in'
elif letter == ' ':
pos = 'out'

print("Size of File is",filesize,'bytes')


print("Lines:", lines)
print("Words:", words)
print("Letters:", letters)

Output:

===== RESTART: C:\Users\HP\AppData\Local\Programs\Python\Python313\ex-1.py =====

Size of File is 35 bytes

Lines: 1

Words: 7

Letters: 34

13. Write a program that accepts a filename of a text file and reports the file's longest line.

def get_longest_line(filename):
large_line = ''
large_line_len = 0

with open(filename, 'r') as f:


for line in f:
if len(line) > large_line_len:
large_line_len = len(line)
large_line = line

return large_line

filename = input('Enter text file Name: ')


print (get_longest_line(filename+".txt"))

Output:

===== RESTART: C:\Users\HP\AppData\Local\Programs\Python\Python313\ex-1.py =====

Enter text file Name: Mydoc===== RESTART:


C:\Users\HP\AppData\Local\Programs\Python\Python313\ex-1.py =====

Size of File is 35 bytes

Lines: 1

Words: 7

Letters: 34

14. Create a binary file with roll number, name and marks. Input a roll number and update details.

def Writerecord(sroll,sname,sperc,sremark):
with open ('StudentRecord.dat','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname,"SPERC":sperc,
"SREMARKS":sremark}
pickle.dump(srecord,Myfile)

def Readrecord():
with open ('StudentRecord.dat','rb') as Myfile:
print("\n-------DISPALY STUDENTS DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print('Percetage',' ','Remarks')
while True:
try:
rec=pickle.load(Myfile)
print(' ',rec['SROLL'],'\t ' ,rec['SNAME'],'\t ',end='')
print(rec['SPERC'],'\t ',rec['SREMARKS'])
except EOFError:
break
def Input():
n=int(input("How many records you want to create :"))
for ctr in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
sperc=float(input("Enter Percentage: "))
sremark=input("Enter Remark: ")
Writerecord(sroll,sname,sperc,sremark)

def Modify(roll):
with open ('StudentRecord.dat','rb') as Myfile:
newRecord=[]
while True:
try:
rec=pickle.load(Myfile)
newRecord.append(rec)
except EOFError:
break
found=1
for i in range(len(newRecord)):
if newRecord[i]['SROLL']==roll:
name=input("Enter Name: ")
perc=float(input("Enter Percentage: "))
remark=input("Enter Remark: ")

newRecord[i]['SNAME']=name
newRecord[i]['SPERC']=perc
newRecord[i]['SREMARKS']=remark
found =1
else:
found=0

if found==0:

print("Record not found")


with open ('StudentRecord.dat','wb') as Myfile:
for j in newRecord:
pickle.dump(j,Myfile)
def main():

while True:
print('\nYour Choices are: ')
print('1.Insert Records')
print('2.Dispaly Records')
print('3.Update Records')
print('0.Exit (Enter 0 to exit)')
ch=int(input('Enter Your Choice: '))
if ch==1:
Input()
elif ch==2:
Readrecord()
elif ch==3:
r =int(input("Enter a Rollno to be update: "))
Modify(r)
else:
break
main()

15. Remove all the lines that contain the character `a' in a file and write it to another file

f1 = open("Mydoc.txt")
f2 = open("copyMydoc.txt","w")
for line in f1:
if 'a' not in line:
f2.write(line)
print('## File Copied Successfully! ##')
f1.close()
f2.close()

f2 = open("copyMydoc.txt","r")
print(f2.read())

Output:

===== RESTART: C:\Users\HP\AppData\Local\Programs\Python\Python313\ex-1.py =====

## File Copied Successfully! ##

16. Write a program to perform read and write operation onto a student.csv file having fields as roll
number, name, stream and percentage.

import csv
with open('Student_Details.csv','w',newline='') as csvf:
writecsv=csv.writer(csvf,delimiter=',')
choice='y'
while choice.lower()=='y':
rl=int(input("Enter Roll No.: "))
n=input("Enter Name: ")
p=float(input("Enter Percentage: "))
r=input("Enter Remarks: ")
writecsv.writerow([rl,n,p,r])
print(" Data saved in Student Details file..")
choice=input("Want add more record(y/n).....")

with open('Student_Details.csv','r',newline='') as fileobject:


readcsv=csv.reader(fileobject)
for i in readcsv:
print(i)

Output:

===== RESTART: C:\Users\HP\AppData\Local\Programs\Python\Python313\ex-1.py =====

Enter Roll No.: 34

Enter Name: subhas

Enter Percentage: 87

Enter Remarks: good

Data saved in Student Details file..

Want add more record(y/n).....n

['34', 'subhas', '87.0', 'good']

17. Program to search the record of a particular student from CSV file on the basis of inputted name.

import csv

#input Roll number you want to search

number = input('Enter number to find: ')


found=0
#read csv, and split on "," the line

with open('Student_Details.csv') as f:
csv_file = csv.reader(f, delimiter=",")
#loop through csv list
for row in csv_file:

#if current rows index value (here 0) is equal to input, print that row
if number ==row[0]:
print (row)
found=1
else:
found=0
if found==1:
pass
else:
print("Record Not found")

Output:

===== RESTART: C:\Users\HP\AppData\Local\Programs\Python\Python313\ex-1.py =====

Enter number to find: 5

Record Not found

18. Write a random number generator that generates random numbers between 1 and 6 (simulates a
dice).

import random
import random

def roll_dice():
print (random.randint(1, 6))

print("""Welcome to my python random dice program!


To start press enter! Whenever you are over, type quit.""")

flag = True
while flag:
user_prompt = input(">")
if user_prompt.lower() == "quit":
flag = False
else:
print("Rolling dice...\nYour number is:")
roll_dice()

Output:

===== RESTART: C:\Users\HP\AppData\Local\Programs\Python\Python313\ex-1.py =====

Welcome to my python random dice program!

To start press enter! Whenever you are over, type quit.

>

Rolling dice...

Your number is:

>

Rolling dice...

Your number is:

>quit
19. Write a python program to implement a stack using a list data-structure.

def isempty(stk):
if stk==[]:
return True
else:
return False

def push(stk,item):
stk.append(item)
top=len(stk)-1

def pop(stk):
if isempty(stk):
return "underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item

def peek(stk):
if isempty(stk):
return "underflow"
else:
top=len(stk)-1
return stk[top]

def display(stk):
if isempty(stk):
print('stack is empty')
else:
top=len(stk)-1
print(stk[top],'<-top')
for i in range(top-1,-1,-1):
print(stk[i])

#Driver Code

def main():
stk=[]
top=None
while True:
print('''stack operation
1.push
2.pop
3.peek
4.display
5.exit''')
choice=int (input('enter choice:'))
if choice==1:
item=int(input('enter item:'))
push(stk,item)
elif choice==2:
item=pop(stk)
if item=="underflow":
print('stack is underflow')
else:
print('poped')
elif choice==3:
item=peek(stk)
if item=="underflow":
print('stack is underflow')
else:
print('top most item is:',item)
elif choice==4:
display(stk)
elif choice==5:
break
else:
print('invalid')
exit()
main()

Output:

===== RESTART: C:\Users\HP\AppData\Local\Programs\Python\Python313\ex-1.py =====

stack operation

1.push

2.pop

3.peek

4.display

5.exit

enter choice:1

enter item:34

stack operation

1.push

2.pop

3.peek
4.display

5.exit

enter choice:1

enter item:67

stack operation

1.push

2.pop

3.peek

4.display

5.exit

enter choice:2

poped

stack operation

1.push

2.pop

3.peek

4.display

5.exit

enter choice:3

top most item is: 34

stack operation

1.push

2.pop

3.peek

4.display

5.exit

enter choice:4

34 <-top

stack operation

1.push

2.pop
3.peek

4.display

5.exit

enter choice:5

20. Write a program to implement a queue using a list data structure.

# Function to check Queue is empty or not


def isEmpty(qLst):
if len(qLst)==0:
return 1
else:
return 0

# Function to add elements in Queue


def Enqueue(qLst,val):
qLst.append(val)
if len(qLst)==1:
front=rear=0
else:
rear=len(qLst)-1

# Function to Delete elements in Queue


def Dqueue(qLst):
if isEmpty(qLst):
return "UnderFlow"
else:
val = qLst.pop(0)
if len(qLst)==0:
front=rear=None
return val

# Function to Display top element of Queue


def Peek(qLst):
if isEmpty(qLst):
return "UnderFlow"
else:
front=0
return qLst[front]

# Function to Display elements of Queue


def Display(qLst):
if isEmpty(qLst):
print("No Item to Dispay in Queue....")
else:
tp = len(qLst)-1
print("[FRONT]",end=' ')
front = 0
i = front
rear = len(qLst)-1
while(i<=rear):
print(qLst[i],'<-',end=' ')
i += 1
print()

# Driver function
def main():
qList = []
front = rear = 0
while True:
print()
print("##### QUEUE OPERATION #####")
print("1. ENQUEUE ")
print("2. DEQUEUE ")
print("3. PEEK ")
print("4. DISPLAY ")
print("0. EXIT ")
choice = int(input("Enter Your Choice: "))
if choice == 1:
ele = int(input("Enter element to insert"))
Enqueue(qList,ele)
elif choice == 2:
val = Dqueue(qList)
if val == "UnderFlow":
print("Queue is Empty")
else:
print("\n Deleted Element was : ",val)

elif choice==3:
val = Peek(qList)
if val == "UnderFlow":
print("Queue is Empty")
else:
print("Item at Front: ",val)

elif choice==4:
Display(qList)
elif choice==0:
print("Good Luck......")
break

main()

Output:

===== RESTART: C:\Users\HP\AppData\Local\Programs\Python\Python313\ex-1.py =====


##### QUEUE OPERATION #####

1. ENQUEUE

2. DEQUEUE

3. PEEK

4. DISPLAY

0. EXIT

Enter Your Choice: 1

Enter element to insert23

##### QUEUE OPERATION #####

1. ENQUEUE

2. DEQUEUE

3. PEEK

4. DISPLAY

0. EXIT

Enter Your Choice: 1

Enter element to insert34

##### QUEUE OPERATION #####

1. ENQUEUE

2. DEQUEUE

3. PEEK

4. DISPLAY

0. EXIT

Enter Your Choice: 2

Deleted Element was : 23

##### QUEUE OPERATION #####

1. ENQUEUE
2. DEQUEUE

3. PEEK

4. DISPLAY

0. EXIT

Enter Your Choice: 3

Item at Front: 34

##### QUEUE OPERATION #####

1. ENQUEUE

2. DEQUEUE

3. PEEK

4. DISPLAY

0. EXIT

Enter Your Choice: 4

[FRONT] 34 <-

##### QUEUE OPERATION #####

1. ENQUEUE

2. DEQUEUE

3. PEEK

4. DISPLAY

0. EXIT

Enter Your Choice: 0

Good Luck......

You might also like