BSC (HONS)
COMPUTER
SCIENCE
PYTHON
BHASKARACHARYA
COLLEGE OF
APPLIED SCIENCES
Amrinder Singh Grewal
2302004
2023-2024
Page 2 of 20
INDEX
[Link] QUESTIONS PAGE
NO.
1. WAP to find the roots of a quadratic equation
2. WAP to accept a number ‘n’ and
a. Check if ’n’ is prime
b. Generate all prime numbers till ‘n’
c. Generate first ‘n’ prime numbers
3. WAP to create a pyramid of the character ‘*’ and a reverse pyramid
4. WAP that accepts a character and performs the following:
a. print whether the character is a letter or numeric digit or a special character
b. if the character is a letter, print whether the letter is uppercase or lowercase
c. if the character is a numeric digit, prints its name in text (e.g., if input is 9, output
is NINE)
5. WAP to perform the following operations on a string
a. Find the frequency of a character in a string.
b. Replace a character by another character in a string.
c. Remove the first occurrence of a character from a string.
d. Remove all occurrences of a character from a string.
6. WAP to swap the first n characters of two strings.
Page 3 of 20
7. Write a function that accepts two strings and returns the indices of all the
occurrences of the second string in the first string as a list. If the second string
is not present in the first string then it should return -1.
8. WAP to create a list of the cubes of only the even integers appearing in the
input list
9. WAP to read a file and
a. Print the total number of characters, words and lines in the file.
b. Calculate the frequency of each character in the file. Use a variable of dictionary
type to maintain the count.
c. Print the words in reverse order.
d. Copy even lines of the file to a file named ‘File1’ and odd lines to another file
named ‘File2
10. WAP to define a class Point with coordinates x and y as attributes. Create
relevant methods and print the objects. Also define a method distance to
calculate the distance between any two point objects.
11. Write a function that prints a dictionary where the keys are numbers between 1
and 5 and the values are cubes of the keys.
12. Consider a tuple t1=(1, 2, 5, 7, 9, 2, 4, 6, 8, 10). WAP to perform following
operations:
a. Print half the values of the tuple in one line and the other half in the next line.
b. Print another tuple whose values are even numbers in the given tuple.
c. Concatenate a tuple t2=(11,13,15) with t1.
d. Return maximum and minimum value from this tuple
Page 4 of 20
13. WAP to accept a name from a user. Raise and handle appropriate exception(s)
if the text entered by the user contains digits and/or special characters.
Page 5 of 20
1. WAP to find the roots of a quadratic equation
SOURCE CODE:-
#program to find roots of quadratic equations
def quad(a,b,c):
#ax^2+bx+c=0
d=(b**2)-(4*a*c)
if d>0:
#two real and distinct roots
x=(-b+(d**0.5))/(2*a)
y=(-b-(d**0.5))/(2*a)
print("real and disinct roots of entered quadratic equation are->>",x,y)
elif d==0:
#one real root
x=-b/(2*a)
print("both roots are equal to->>",x)
else:
#imaginary roots
x=-b/(2*a)
y=((-d)**0.5)/(2*a)
print("roots are",x,"+",y,"i","and",x,"-",y,"i")
a=float(input("enter coefficient of x^2->>"))
b=float(input("enter coefficient of x->>"))
c=float(input("enter coefficient of 1->>"))
quad(a,b,c)
OUTPUT-:
Page 6 of 20
enter coefficient of x^2->>1
enter coefficient of x->>-5
enter coefficient of 1->>6
real and disinct roots of entered quadratic equation are->> 3.0 2.0
2. WAP to accept a number ‘n’ and
a. Check if ’n’ is prime
b. Generate all prime numbers till ‘n’
c. Generate first ‘n’ prime numbers
This program may be done using functions
SOURCE CODE:-
#checking entered number is prime or not
def primecheck(n):
ctr=0
for i in range(1,n+1):
if n%i==0:
ctr+=1
if ctr==2:
return True
#printing all prime number till n
def allprime(n):
print("all prime numbers till",n,"are:")
for i in range(1,n+1):
ctr=0
for j in range(1,i+1):
if i%j==0:
Page 7 of 20
ctr+=1
if ctr==2:
print(i)
def firstprime(n):
print("first",n,"prime numbers are")
num=2
count=0
while count<n:
if primecheck(num):
print(num,end=" ")
count+=1
num+=1
n=int(input("enter number:"))
A=primecheck(n)
print("entered number is prime number:")
allprime(n)
firstprime(n)
OUTPUT-:
enter number:5
entered number is prime number:
all prime numbers till 5 are:
first 5 prime numbers are 2 3 5 7 11
Page 8 of 20
3. WAP to create a pyramid of the character ‘*’ and a reverse pyramid
SOURCE CODE:-
#program to print pyramid of stars
def pyramid(n):
for i in range(1,n+1):
sp=" "*(n-i)
star="*"*(2*i-1)
print(sp+star)
def revpyramid(n):
for i in range(n,0,-1):
sp=" "*(n-i)
star="*"*(2*i-1)
print(sp+star)
n=int(input("enter number of rows->"))
pyramid(n)
revpyramid(n)
enter number of rows->5
***
*****
*******
*********
*******
*****
Page 9 of 20
***
4. WAP that accepts a character and performs the following:
a. print whether the character is a letter or numeric digit or a special character
b. if the character is a letter, print whether the letter is uppercase or lowercase
c. if the character is a numeric digit, prints its name in text (e.g., if input is 9,
output is NINE)
SOURCE CODE:-
#program that print whether the character is a letter or numeric digit or a special character
def chr(n):
if [Link]()==True:
print("ENTERED CHARACTER IS LETTER")
a=cases(n)
elif [Link]()==True:
print("entered character is numeric digit")
a=txt(n)
else:
print("enter charcter is special character")
def cases(n):
if [Link]()==True:
print("LETTER IS UPPERCASE")
else:
print("letter is lowercase")
return n
Page 10 of 20
def txt(n):
if n==1:
print("one")
elif n==2:
print("two")
elif n==3:
print("three")
elif n==4:
print("four")
elif n==5:
print("five")
elif n==6:
print("six")
elif n==7:
print("seven")
elif n==8:
print("eight")
else:
print("nine")
return n
n=input('Enter a charcter->>')
if len(n)<2:
chr(n)
else:
print("enter a single character not a word !!")
OUTPUT
Page 11 of 20
Enter a charcter->>6
entered character is numeric digit
nine
5. WAP to perform the following operations on a string
a. Find the frequency of a character in a string.
b. Replace a character by another character in a string.
c. Remove the first occurrence of a character from a string.
d. Remove all occurrences of a character from a string .
SOURCE CODE:-
#program performing operations on string
def feq(str):
n=input("ENTER A CHARACTER WHOSE FREQUENCY YOU WANT TO DISPLAY--->>>")
if n in str:
ctr=[Link](n)
print("frequency of",n,"is",ctr)
def replace(str):
oldchr=input("enter the charcter you want to replace->>")
newchr=input("enter new character which will replace old character->>")
a=[Link](oldchr,newchr)
print(a)
def remove(str):
firstocc=input("Enter the charcter you want to remove;")
if firstocc in str:
rem=[Link](firstocc,"",1)
print(rem)
def removeall(str):
Page 12 of 20
firstocc=input("Enter the charcter you want to remove;")
if firstocc in str:
rem=[Link](firstocc,"",)
print(rem)
str='Hello pythoon'
feq(str)
replace(str)
remove(str)
removeall(str)
Output:-
ENTER A CHARACTER WHOSE FREQUENCY YOU WANT TO DISPLAY--->>>l
frequency of l is 2
enter the charcter you want to replace->>h
enter new character which will replace old character->>a
Hello pytaoon
Enter the charcter you want to remove;e
Hllo pythoon
Enter the charcter you want to remove;o
Hell pythn
6. WAP to swap the first n characters of two strings.
SOURCE CODE:-
#swaping n characters
def swap():
str1=input("enter first string->>")
str2=input("enter second string->>")
n=int(input("how many numbers you want to swap->>"))
Page 13 of 20
if n<len(str1) and n<len(str2):
newstr1=str2[:n]+str1[n:]
newstr2=str1[:n]+str2[n:]
print(newstr1,newstr2)
swap()
OUTPUT
enter first string->>PYTHON
enter second string->>JAVA
how many numbers you want to swap->>2
JATHON PYVA
>>>
7. Write a function that accepts two strings and returns the indices of
all the occurrences of the second string in the first string as a list. If
the second string is not present in the first string then it should return
-1.
SOURCE CODE:-
str1=input("enter first string->>")
str2=input("enter second string->>")
print([Link](str2))
OUTPUT
enter first string->>notebook
enter second string->>book
>>>
enter first string->>notebook
Page 14 of 20
enter second string->>register
-1
8. WAP to create a list of the cubes of only the even integers
appearing in the input list (may have elements of other types also)
using the following:
a. 'for' loop
b. list comprehension
SOURCE CODE:-
def cubes(lst):
list=[]
for i in lst:
if i%2==0:
[Link](i**3)
return list
n= int(input("how many integers you want to enter::"))
lst=[]
for i in range(n):
x=int(input("enter integer to be entered"))
[Link](x)
print(lst)
a=cubes(lst)
print("list of cubes->>",a)
#LIST COMPREHENSION
def cubes1(lst):
list=[x**3 for x in lst if x %2==0]
print( "list using list comprehension-->>",list)
Page 15 of 20
cubes1(lst)
Output
how many integers you want to enter::5
enter integer to be entered1
enter integer to be entered2
enter integer to be entered4
enter integer to be entered7
enter integer to be entered10
[1, 2, 4, 7, 10]
list of cubes->> [8, 64, 1000]
list using list comprehension-->> [8, 64, 1000]
9. WAP to read a file and
a. Print the total number of characters, words and lines in the file.
b. Calculate the frequency of each character in the file. Use a variable of dictionary
type to maintain the count.
c. Print the words in reverse order.
d. Copy even lines of the file to a file named ‘File1’ and odd lines to another file
named ‘File2’.
[Link]
SOURCE CODE:-
def filereading():
with open("[Link]","r") as fobj:
Page 16 of 20
ctr=[Link]()
char=len(ctr)
words=len([Link]())
lines=[Link]('\n')+1
print("Total characters-->>",char,"Total words-->>",words,"Total lines-->>",lines)
def freq():
with open("[Link]","r") as fobj:
d={}
ctr=[Link]()
for i in ctr:
if i not in d:
d[i]=[Link](i)
print(d)
def rev():
with open("[Link]","r") as fobj:
ctr=[Link]()
x=[Link]()
reversed_words=' '.join(reversed(x))
print("words in reversed order",reversed_words)
filereading()
freq()
rev()
OUTPUT:-
Total characters-->> 46 Total words-->> 7 Total lines-->> 3
Page 17 of 20
{'H': 2, 'e': 2, 'l': 4, 'o': 3, ' ': 5, 'p': 2, 'y': 1, 't': 1, 'h': 2, 'n': 3, '!': 3, '\n': 2, 'T': 1, 'i': 4, 's': 2, 'F':
1, 'a': 2, 'd': 1, 'g': 2, 'r': 2, 'm': 1}
words in reversed order are ->> program Handling File is This python!!! Hello
10. WAP to define a class Point with coordinates x and y as attributes.
Create relevant methods and print the objects. Also define a method
distance to calculate the distance between any two point objects.
import math
class point:
def __init__(self,x,y):
self.x=x
self.y=y
def print_point(self):
print(f"point: ({self.x},{self.y})")
def distance(self,other_point):
dx=self.x-other_point.x
dy=self.y-other_point.y
return [Link](dx**2 + dy**2)
point1=point(1, 2)
point2=point(3, 4)
point1.print_point()
point2.print_point()
distance=[Link](point2)
print(f"Distance between points:{distance}")
output:-
point: (1,2)
point: (3,4)
Distance between points:2.8284271247461903
Page 18 of 20
11. Write a function that prints a dictionary where the keys are
numbers between 1 and 5 and the values are cubes of the keys.
d={}
for i in range(1,6):
d[i]=i**3
print(d)
OUTPUT:-
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
>>>
12. Consider a tuple t1=(1, 2, 5, 7, 9, 2, 4, 6, 8, 10). WAP to perform
following operations:
a. Print half the values of the tuple in one line and the other half in the next line.
b. Print another tuple whose values are even numbers in the given tuple.
c. Concatenate a tuple t2=(11,13,15) with t1.
d. Return maximum and minimum value from this tuple
t1=(1,2,5,7,9,2,4,6,8,10)
def half(t1):
a=len(t1)
for i in range(0,a//2):
print(t1[i],end=" ")
print()
for j in range(a//2,a):
print(t1[j],end=" ")
print()
def newtup(t1):
t2=tuple(num for num in t1 if num %2==0)
Page 19 of 20
print("tuple of even numbers:",t2)
def concat(t1):
t2=(11,13,15)
print(t1+t2)
def values(t1):
xmax=max(t1)
xmin=min(t1)
print(xmax,xmin)
half(t1)
newtup(t1)
concat(t1)
values(t1)
OUTPUT:-
12579
2 4 6 8 10
tuple of even numbers: (2, 2, 4, 6, 8, 10)
(1, 2, 5, 7, 9, 2, 4, 6, 8, 10, 11, 13, 15)
10 1
>>>
13. WAP to accept a name from a user. Raise and handle appropriate
exception(s) if the text entered by the user contains digits and/or
special characters.
def errors(name):
if not [Link]():
Page 20 of 20
raise ValueError("Invalid characters in name. PLEASE ENTER ONLY ALPHABETS IN NAME")
try:
name=input("Enter a name->>")
errors(name)
print("accepted",name)
except ValueError as a:
print(f"Error: {a}")
OUTPUT:-
Enter a name->>Amrinder
accepted Amrinder
>>>
================= RESTART: C:\Users\admin\Desktop\python\[Link] ================
Enter a name->>Ammy9
Error: Invalid characters in name. PLEASE ENTER ONLY ALPHABETS IN NAME
>>>