0% found this document useful (0 votes)
10 views

Computer Science Practical File

Python programs

Uploaded by

luckydada1238
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)
10 views

Computer Science Practical File

Python programs

Uploaded by

luckydada1238
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/ 22

1.WAP to print palindrome numbers from 1 to 100.

#PROGRAM TO PRINT PALINDROME NUMBERS FROM 1 TO


100
while True:
for num in range(1,101):
rev = 0
orig = num
while (num != 0):
rem = num % 10
rev = rev * 10 + rem
num = num // 10
if orig == rev:
print(orig, ‘is palindrome’)

Output:
1 is palindrome
2 is palindrome
3 is palindrome
4 is palindrome
5 is palindrome
6 is palindrome
7 is palindrome
8 is palindrome
9 is palindrome
11 is palindrome
22 is palindrome
33 is palindrome
44 is palindrome
55 is palindrome
66 is palindrome
77 is palindrome
88 is palindrome
99 is palindrome

2.WAP to display the following pattern.


P
Py
Pyt
Pyth
Pytho
Python

#PROGRAM TO DISPLAY A PATTERN


word = ‘Python’
x=‘’
for i in word:
x=x+i
print(x)

Output:
P
Py
Pyt
Pyth
Pytho
Python
6.WAP to find the factorial of a number by using
function.

#PROGRAM TO FIND THE FACTORIAL OF A NUMBER


def factorial(num):
factorial = 1
for i in range(1, num + 1):
factorial *= i
print(‘The factorial of’, num, ‘is’, factorial)
num = int(input(‘Enter a number: ’))
factorial(num)

Output:
Enter a number: 5
The factorial of 5 is 120
11.Write a function in python that counts the
number of Me/My words present in a text file
Story.txt. Consider the following content: “My first
book was me and my family. It gave me a chance to be
known to the world.”

#PROGRAM TO COUNT THE NUMBER OF ME/MY PRESENT


IN A TEXTFILE
def countMeMy():
c=0
F=open(‘Story.txt’, ‘r’)
data= F.read()
words=data.split()
for i in words:
if (i== ‘Me’ or if i== ‘me’) or if i== ‘My’:
Cc=c+1
print(“Count of Me/My in the file ’,c)
F.close()
countMeMy()
Output:
Count of Me/My in the file: 4

4.WAP that copies one dictionary to another.

#PROGRAM TO COPY ONE DICTIONARY TO ANOTHER


DICTIONARY
origdict = {}
n = int(input(‘Enter the number of elements you want to
add: ‘))
for i in range(n):
key = input(‘Enter key: ’)
values = input(‘Enter values: ’)
origdict[key] = values.split()
print(‘Original dictionary: ’, origdict)
newdict = dict(origdict)
print(‘Copied dictionary: ’, newdict)

Output:
Enter the number of elements you want to add: 4
Enter key: Adm No
Enter values: 3356 3258 3483
Enter key: Name
Enter values: Aarju Mohini Gauri
Enter key:Class
Enter values: 12 12 12
Enter key: Stream
Enter values: PCB PCM PCB
Original dictionary: {‘Adm No’: [‘3356’, ‘3258’, ‘3483’],
‘Name’: [‘Aarju’, ‘Mohini’, ‘Gauri’], ‘Class’: [‘12’, ‘12’,
‘12’], ‘Stream’: [‘PCB’, ‘PCM’, ‘PCB’]}
Copied dictionary: {‘Adm No’: [‘3356’, ‘3258’, ‘3483’],
‘Name’: [‘Aarju’ ‘Mohini’, ‘Gauri’], ‘Class’: [‘12’, ‘12’,
‘12’], ‘Stream’: [‘PCB’ ‘PCM’, ‘PCB’]}

5.WAP to implement simple calculator by using


function.

#PROGRAM TO IMPLEMENTED A SIMPLE CALCULATOR


def add(x, y): #add numbers
return x + y
def subtract(x, y): #subtract numbers
return x – y
def multiply(x, y): multiply numbers
return x * y
def divide(x, y): divide numbers
return x / y
choice = 0
ch = ‘y’
while ch == ‘y’:
print(‘Select operation.’)
print(‘1.Add’)
print(‘2.Subtract’)
print(‘3.Multiply’)
print(‘4.Divide’)
print(‘5.Exit’)
choice = int(input(‘Enter your choice: ’))
try:
if choice in (1, 2, 3, 4):
num1 = int(input(‘Enter first number: ’))
num2 = int(input(‘Enter second number: ’))
except ValueError:
print(‘Invalid input. Please enter a number.’)
continue

if choice == 1:
print(num1, ‘+’, num2, ‘=’, add(num1, num2))
elif choice == 2:
print(num1, ‘-’, num2, ‘=’, subtract(num1, num2))
elif choice == 3:
print(num1, ‘*’, num2, ‘=’, multiply(num1, num2))
elif choice == 4:
print(num1, ‘/’, num2, ‘=’, divide(num1, num2))
elif choice == 5:
print(‘Exit program’)
break
else:
print(‘Invalid Choice’)

Output:
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
5.Exit
Enter your choice: 1
Enter first number: 34
Enter second number: 54
34 + 54 = 88
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
5.Exit
Enter your choice: 2
Enter first number: 79
Enter second number: 43
79 – 43 = 36

Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
5.Exit
Enter your choice: 3
Enter first number: 24
Enter second number: 12
24 * 12 = 288
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
5.Exit
Enter your choice: 4
Enter first number: 45
Enter second number: 5
45 / 5 = 9.0
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
5.Exit
Enter your choice: 5
Exit program

7.Write a function that print all the prime numbers


between 0 and limit where limit is the parameter.
#PROGRAM TO PRINT PRIME NUMBERS BETWEEN 0 AND
LIMIT
def prime(limit):
for num in range(2, limit+1):
for i in range(2, int(num**0.5)+1):
if (num%i) == 0:
break
else:
print(num)
limit=int(input(‘Enter upper range: ‘))
prime(limit)

Output:
Enter upper range: 10
2
3
5
7
8.WAP using a function to accept characters in a
list then find and display vowels present in the list.

#FUNCTION TO DISPLAY VOWELS


def disp_vowels():
user_input = input(‘Enter a list of characters: ’)
data = user_input.split()
for char in data:
if char in ‘aeiouAEIOU’:
print(char)
disp_vowels()

Output:
Enter a list of characters: a f e g I m u s
a
e
I
u
9.WAP that takes a string as input and count the
number of uppercase and lowercase letters
present in the string by using function.

#PROGRAM TO COUNT UPERCASE AND LOWERCASE


LETTERS IN A STRING
def count_upper_lower(str):
UC=0
LC=0
for i in str:
if i.isupper():
UC=UC+1
elif i.islower():
LC=LC+1
print(‘Number of upper case letters: ’, UC)
print(‘Number of lower case letters: ’, LC)
str=input(‘Enter the string: ’)
count_upper_lower(str)

Output:
Enter the string: Write a Python Program
Number of upper case letters: 3
Number of lower case letters: 16
10.Write a function in python to create a text file
Story.txt.

#FUNCTION TO CREATE A TEXT FILE


def create_File():
try:
F=open(‘Story.txt’, ‘w’)
data=input(‘Enter file c ’)
F.writelines(data)
print(‘File created successfully.’)
F.close()
except:
print(‘Error occurred’)

Output:
Enter file content: My first book was me and my
family. It gave me
a chance to be known to the world.
File created successfully.
12.Write a function in python to count the number
of lines in a text file Story.txt that are starting
with an alphabet ‘A’. Consider the following
content: “A boy is playing there. There is a playground.
An aeroplane is in the sky. Alphabets and numbers are
allowed in password.”

#PROGRAM TO COUNT THE NUMBER OF LINES STARTING


WITH ALPHABET ‘A’
def countLines():
File = open(‘Story.txt’, ‘r’)
lines = File.readlines( )
count = 0
for word in lines:
if word[0] == ‘a’ or word[0] == ‘A’:
count = count + 1
print(‘Total number of lines starting from alphabet
‘a’’, count)
countLines()
Output:
Total number of lines starting from alphabet ‘a’: 3

13.WAP to read and append data in a binary file


Sports.dat

#PROGRAM TO READ AND APPEND DATA IN BINARY FILE


import pickle
def bf_read():
try:
with open(‘Sports.dat’, ‘rb’) as F:
existing_data = pickle.load(F)
for i in existing_data:
print(‘Existing records’)
print(‘Player code: ’, i[0])
print(‘Player name: ’, i[1])
print(‘Player score: ’, i[2])
print(‘Player rank: ’, i[3])
except:
print(‘Terminate the file’)
def bf_append():
try:
existing_data = []
with open(‘Sports.dat’, ‘ab’) as F:
print(‘Append data’)
Pcode=int(input(‘Enter player code: ’))
Pname=input(‘Enter player name: ’)
Score=int(input(‘Enter player score: ’))
Rank=int(input(‘Enter player rank: ’))
data=[Pcode, Pname, Score, Rank]
existing_data.append(data)
pickle.dump(existing_data, F)
except:
print(‘Terminate the file’)

Output:
Existing records
Player code: 5678
Player name: Dev
Player score:358
Player rank: 4
Append data
Enter player code: 3356
Enter player name: Chah
Enter player score: 423
Enter player rank: 3

14.Write a function to search in a binary file


Sports.dat

#FUCTION TO SEARCH RECORDS IN BINARY FILE


import pickle
def bf_search():
with open(‘Sports.dat’, ‘rb’) as F:
print(‘Data stored in a file’)
Pcode = int(input(‘Enter the player code ‘))
try:
while True:
data = pickle.load(F)
for i in data:
if i[0] == Pcode:
print(‘Record found’)
print(‘Player name: ’, i[1])
print(‘Player score: ’, i[2])
print(‘Player rank: ’, i[3])
except EOFError:
F.close()
bf_search()

Output:
Data Stored in a file
Enter the player code: 5678
Record found
Player name: Dev
Player score: 358
Player rank: 4

15.Write a function to update a binary file


Sports.dat

#FUNCTION TO UPDATE A BINARY FILE


import pickle
def bf_update():
F = open(‘Sports.dat’, ‘rb’)
F1 = open(‘Sports.dat’, ‘wb’)
Pcode = int(input(‘Enter the player code to be
updated: ’))
F.seek(0)
while True:
current_pos = F.tell()
try:
data = pickle.load(F)
for i in data:
if i[0] == Pcode:
print(‘Update the file’)
i[1] = input(‘Enter player name: ’)
i[2] = int(input(‘Enter player score: ’))
i[3] = int(input(‘Enter player rank: ’))
F.seek(current_pos)
break
except EOFError:
break
F.close()
Output:
Enter the player code to be
Updated: 5678
Update the file
Enter player name: Dev
Enter player score: 467
Enter player rank: 3

16.Write a function to delete binary file Sports.dat


#FUNCTION TO DELETE BINARY FILE
import pickle
def bf_delete():
F=open(‘Sports.dat’, ‘rb’)
F1=open(‘Sports.dat’, ‘wb’)
data=pickle.load(F)
Pcode=int(input(‘Enter the player code: ’))
L=[]
for i in data:
if i[0]==Pcode:
L.append(i)
pickle.dump(L,F1)
print(‘File deleted!’)
bf_delete()

Output:
Enter the player code: 5678
File deleted!
17.A binary file Book.dat has structure:
[Bookno, Bookname, Author, Price]
i)Write a user defined function createFile() to
input data for a
record and add to Book.dat.

#FUNCTION TO INPUT AND ADD DATA TO BINARY FILE


import pickle
def createFile():
F=open(‘Book.dat’, ‘ab’)
Bookno=int(input(‘Enter book number: ’))
Bookname=input(‘Enter book name: ’)
Author=input(‘Enter book author: ’)
Price=int(input(‘Enter book price: ’))
L=[Bookno, Bookname, Author, Price]
pickle.dump(L,F)
F.close()

Output:
Enter book number: 083
Enter book name: Comp. Sc.
Enter book author: Sumita Arora
Enter book price: 675
ii)Write a function countRec() which accepts the
author name as
parameter and count and return the number of
books by the
given author stored in the binary file Book.dat.

#FUNCTION TO COUNT AND RETURN NUMBER OF BOOKS


BY AUTHOR IN BINARY FILE
import pickle
def countRec():
F=open(‘Book.dat’, ‘rb’)
data=pickle.load(F)
author=input(‘Enter book author: ’)
count=0
for i in data:
if i[2]==author:
count+=1
print(“Number of books given by”, author, “:”, count)
F.close()

Output:
Enter book author: Sumita Arora
Number of books given by Sumita Arora: 2

You might also like