CS Prac cal File
#Basic python programes
Q1 ) WAP to obtain three numbers and print their sum
Ans-
num1= oat(input("enter number 1:”))
num2= oat(input("enter number 2:")
num3= oat(input("enter number 3:"))
sum=num1+num2+num3
print("three numbers are:",num1,num2,num3)
print("sum is:",sum)
Output-
fl
fl
fl
ti
Q2) WAP to obtain length and breadth of a rectangle and calculate its area
Ans-
breadth= oat(input("enter breadth of the rectangle:"))
length= oat(input("enter length of the triangle:"))
print("length:",length)
print("breadth:",breadth)
area=length*breadth
print("area of rectangle=",area)
Output-
fl
fl
Q3) WAP to calculate BMI of a person. Body mass index is a simple
calcula on using a person’s height and weight. The formula is BMI=kg/m^2
where kg is person’s weight in kilograms and m^2 is their height in metres
square.
Ans-
weight = oat(input("enter weight in kg-",))
height= oat(input("enter height in meters:"))
print("height:",height)
print("weight:",weight)
bmi=weight/height**2
print("bmi is",bmi)
Output-
ti
fl
fl
Q4) WAP to input a value in kilometre and convert it into
miles(1km=0.621371)
Ans-
km= oat(input("enter kilometer:"))
miles=km*0.621371
print("kilometer:",km)
print("miles:",miles)
Output-
fl
Q5) WAP to input the number of hours studied in a single day. Display the
output in minutes with proper statements.
Ans-
x=int(input("Enter the number of hours studied:"))
y=x*60
print("The total number of minutes studied is",y)
Output-
#Python Nested Looping Programes
Q1) WAP to display the pa ern using nested looping
*
**
***
****
*****
Ans-
n=int(input("Enter the rows:"))
for i in range(1,n+1):
for j in range(1,i+1):
print("*",end=" ")
print()
Output-
tt
Q2) WAP to display the pa ern using nested looping
*****
****
***
**
*
Ans-
n=int(input("Enter the rows:"))
for i in range(1,n+1):
for j in range(i,n+1):
print("*",end=" ")
print()
Output-
tt
Q3) WAP to display the pa ern using nested looping
****
****
****
****
Ans-
n=int(input("Enter the rows:"))
for i in range(1,n+1):
for j in range(n):
print("*",end=" ")
print()
Output-
tt
Q4) WAP to display the pa ern using nested looping
1
12
123
1234
12345
Ans-
n=int(input("Enter the rows:"))
for i in range(1,n+1):
for j in range(1,i+1):
print(j,end=" ")
print()
Output-
tt
Q5) WAP to display the pa ern using nested looping
1
22
333
4444
55555
Ans-
n=int(input("Enter the rows:"))
for i in range(1,n+1):
for j in range(1,i+1):
print(i,end=" ")
print()
Output-
tt
# Python Looping Constructs
Q1) WAP to print rst ten natural numbers
Ans-
i=1
while i<=10:
print(i)
i+=1
Output-
fi
Q2) WAP to print rst ten even numbers
Ans-
for i in range(2,21,2):
print(i)
Output-
fi
Q3) WAP to print rst ten odd numbers
Ans-
for i in range(1,20,2):
print(i)
Output-
fi
Q4) WAP to print rst ten natural numbers in reverse order
Ans-
for i in range(10,0,-1):
print(i)
Output-
fi
Q5) WAP to input the maximum value from the user and display the coun ng
ll that maximum number
Ans-
a=int(input("Enter the number:”))
for i in range(1,a+1):
print(i)
Output-
ti
ti
#Python Condi onal Statements
Q1) WAP to input your age and display the message- “you are an adult”
Ans-
age=int(input("Enter your age:"))
if age>=18:
print("The person is an adult")
else:
print("The person is not an adult")
Output-
ti
Q2) WAP to enter year and check whether if it is a leap year or not. Display
the output
Ans-
y=int(input("Enter the year:”))
if y%4==0:
print("The year in a leap year")
else:
print("The year is not a leap year")
Output-
Q3) WAP to input a numeric value; check whether it is a posi ve,nega ve or
equal to zero
Ans-
num=int(input("Enter the number:"))
if num >=0:
print("The number is a positve number")
else:
print("the number is a nega ve number")
Output-
ti
ti
ti
Q4) WAP to accept a number. Check whether it is an even or odd number
Ans-
num=int(input("Enter the number:"))
if num%2==0:
print("The number is an even number")
elif num%2!=0:
print("The number is an odd number")
Output-
Q5) WAP to check whether a number is divisible by 7 or not
Ans-
num=int(input("Enter the number:"))
if num%7==0:
print("Number is divisible")
else:
print("Number is not divisible")
Output-
#Python String Manipula on
Q1) WAP to count number of mes a character occurs in the given string
Ans-
n=input("Enter string:")
a=input("Enter the character to count:")
b=[Link](a)
print(a,"occurs",b," mes")
Output-
ti
ti
ti
Q2) WAP which replaces all vowels in the string with ‘*’.
Ans-
n=input("Enter string:")
nl=(" ")
for ch in n:
n2=[Link]()
if n2=='a'\
or n2=='e'\
or n2=='i'\
or n2=='o'\
or n2=='u':
nl+='*'
else:
nl+=ch
print(nl)
Output-
Q3) WAP which reverses a string and stores the reversed string in a new
string
Ans-
n=input("Enter string:")
nl=""
for ch in n:
n2=ch+nl
nl=n2
print(nl)
Output-
Q4) WAP to convert a string with more than one word into tle case string
where string is to be entered by the user.
Ans-
n=input("Enter tle:")
if"" in n:
tn=n. tle()
print("The tle case string is:",tn)
else:
print("The entetred string does not contain more than one [Link]
conversion performed")
Output-
ti
ti
ti
ti
Q5) Input a string having some digits. Write a program to return the sum of
digits present in this string
Ans-
n = input("Enter string: ")
nl = 0
for ch in n:
if [Link]():
nl += int(ch)
print("sum of digits:", nl)
Output-
#Introduc on To Python Modules
Q1) The formula E=mc2 states that the equivalent energy (E) can be calculated
as the mass (m) mul plied by the speed of light (c=about 3 X 108m/s) squared
.Write a program that accepts the mass of an object and determines its
energy.
Ans-
import math
m= oat(input("Enter mass:"))
c=3*pow(10,8)
E=m*c*c
print("Equivalent energy:”,E,"Joule")
Output-
fl
ti
ti
Q2)In a school fest, three randomly chosen students out of 100 students
(having roll numbers 1-100) have to present bouquets to the guests. Help the
school authori es choose three students randomly.
Ans-
import random
student1=[Link](1,100)
student2=[Link](1,100)
student3=[Link](1,100)
print("3 chosen students are:",)
print(student1,student2,student3)
Output-
ti
Q3)Given a list containing these values[22,13,28,13,22,25,7,4,13,25]. Write a
code to calculate mean, median and mode of this list.
Ans-
import sta s cs as stat
list1=[22,13,28,13,22,25,7,4,13,25]
list_mean=[Link](list1)
list_median=[Link](list1)
list_mode=[Link](list1)
print("Given list:",list1)
print("Mean:",list_mean)
print("Median:",list_median)
print(“Mode:",list_mode)
Output-
ti
ti
Q4)Write a program that generates six random numbers in a sequence
created with (start, stop, step). Then print mean, median and mode of the
generated numbers.
Ans-
import random
import sta s cs
start = 1
stop = 50
step = 3
numbers = [[Link](start, stop, step) for _ in range(6)]
print("Generated numbers:", numbers)
mean = sta s [Link](numbers)
median = sta s [Link](numbers)
try:
mode = sta s [Link](numbers)
except sta s [Link] s csError:
mode = "No unique mode"
print("Mean:", mean)
print("Median:", median)
print("Mode:", mode)
Output-
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
Q5)Write a code fragment to generate two random integers between 450 and
[Link] these numbers along with their average.
Ans-
import random
num1 = [Link](450, 950) - 450
num2 = [Link](450, 950) - 450
avg = (num1 + num2)/2
print("Random integers in the range 450 to 950 :", num1, num2)
print("Their average :", avg)
Output-
#Flow Of Control
Q1)Write a program to input a number and then print its rst and last digit
raised to the length of the number (the number of digits in the number is the
length of the number).
Ans-
import math
num = int(input("Enter a number : "))
ln = len( str(num)) # length of the number
lst = num % 10
fst = num // [Link](10, ln-1)
print("Length of given number", num, "is", ln)
print("The rst digit is ", fst)
print("The last digit is ", lst)
print("First digit raised to the length :", \
[Link](fst, ln))
print("Last digit raised to the length :", \
[Link](lst, ln))
Output-
fi
fi
Q2)Input three angles and determine if they form a triangle or not.
Ans-
angle1 = angle2 = angle3 = 0
angle1 = oat(input("Enter angle 1 : "))
angle2 = oat(input("Enter angle 2 : "))
angle3 = oat(input("Enter angle 3 : "))
if (angle1 + angle2 + angle3) == 180 :
print("Angles form a triangle.")
else:
print("Angles do not form a triangle.”)
Output-
fl
fl
fl
Q3) Write a program to check if a given number is a palindrome number or
not.
Ans-
num = int(input("Enter number:"))
wnum = num # working number stores num ini ally
rev = 0
while(wnum > 0):
dig = wnum % 10
rev = rev*10 + dig
wnum = wnum // 10
if(num == rev):
print("Number", num, "is a palindrome!")
else:
print("Number", num,"is not a palindrome!”)
Output-
ti
Q4)Write a program to print Fibonacci series.
Ans-
t = int(input("How many terms?(enter 2+ value): "))
rst = 0
second = 1
print("\nFibonacci series is:")
print( rst, ",", second, end=", ")
for i in range(2, t):
next = rst + second
print(next, end=", ")
rst = second
second = next
Output-
fi
fi
fi
fi
Q5)Write a program to nd sum of the series :
s = 1 + x + x² + x³ + … + xⁿ (Input the values of x and n)
Ans-
x = oat(input("Enter value of x : "))
n = int(input("Enter value of n (for x ** n) : "))
s=0
for a in range(n + 1) :
s += x ** a
print("Sum of rst", n, "terms :", s)
Output-
fl
fi
fi
#String Manipula on
Q1)Write a program that asks a user for a username and a pcode. Make sure
that pcode does not contain username and matches ‘Trident111'.
Ans-
uname = input("Enter user name :")
pcode = input("Enter code :")
if uname not in pcode and pcode == 'Trident111' :
print("Your code is Valid to proceed.")
else :
print("Your code is Not Valid.”)
Output-
ti
Q2)Write a program to input a string and print number of upper- and lower-
case le ers in it.
Ans-
str1 = input("Enter a string: ")
ucase, lcase = 0, 0
for ch in str1:
if ch >= 'A' and ch <= 'Z':
ucase += 1
if ch >= 'a' and ch <= 'z':
lcase += 1
print("[Link] uppercase le ers:", ucase)
print("[Link] lowercase le ers:", lcase)
Output-
tt
tt
tt
Q3)Write a program to input a string and check if contains a digit or not.
Ans-
strg = input("Enter a string :")
test = False
dig = "0123456789"
for ch in strg:
if ch in dig:
print("The string contains a digit.")
test = True
break
if test == False:
print("The string doesn't contain a digit.”)
Output-
Q4)Write a program that removes all capitaliza on and common punctua on
from a string s.
Ans-
s = input("Enter a string : ")
s = [Link]()
punctua on = "!.,&?"
nal_str = ""
for ch in s:
if ch not in punctua on:
nal_str += ch
print("Final string :", nal_str)
Output-
fi
fi
ti
fi
ti
ti
ti
Q5)Write a program that asks the user for a string and creates a new string
that doubles each character of the original string. For instance, if the user
enters Sipo, the output should be SSiiippoo
Ans-
s = input("Enter a string :")
ds = ""
for c in s:
ds = ds + c*2
print("Original string:", s)
print("Doubled string:", ds)
Output-
#List Manipula on
Q1)Write a program that inputs a list, replicates it twice and then prints the
sorted list in ascending and descending orders.
Ans-
val = eval(input("Enter a list :"))
print("Original list :", val)
val = val * 2
print("Replicated list :", val)
[Link]()
print("Sorted in ascending order :", val)
[Link](reverse = True)
print("Sorted in descending order :", val)
Output-
ti
Q2)Program to nd the minimum element from a list of element along with
its index in the list.
Ans-
lst = eval(input("Enter list : "))
length = len(lst)
min_ele = lst[0]
min_index = 0
for i in range(1, length) :
if lst[i] < min_ele :
min_ele = lst[i]
min_index = i
print("Given list is :", lst)
print("The minimum element of the given list is :")
print(min_ele, "at index", min_index)
Output-
fi
Q3)Write a program to input a list of numbers and swap elements at the even
loca on with the elements at the odd loca on.
Ans-
val = eval(input("Enter a list :"))
print("Original list is :", val)
s = len(val)
if s % 2 != 0 :
s=s-1
for i in range(0, s, 2) :
print(i, i+1)
val[i], val[i+1] = val[i+1], val[i]
print("List a er swapping :", val)
Output-
ti
ft
ti
Q4)Program to search for an element in a given list of numbers.
Ans-
lst = eval(input("Enter list :"))
length = len(lst)
element = int(input("Enter element to be searched for :"))
for i in range(0, length) :
if element == lst[i] :
print(element, "found at index", i)
break
else:
print(element, "not found in given list”)
Output-
Q5)Program to count the frequency of a given element in a list of numbers.
Ans-
lst = eval(input("Enter list :"))
length = len(lst)
element = int(input("Enter element :"))
count = 0
for i in range(0, length):
if element == lst[i]:
count += 1
if count == 0:
print(element, "not found in given list")
else:
print(element, "has frequency as", count, "in given list”)
Output-
#Tuples
Q1)Write a program to input a tuple and create two new tuples from it, one
containing its every 3rd element in reverse order, star ng from the last
element another containing every alternate elements lying between 3rd to
9th elements.
Ans-
tup = eval(input("Enter input for tuple : "))
t1 = tup[::-3]
t2 = tup[Link]
print("Two created tuples are:")
print("Tuple 1 :", t1)
print("Tuple 2 :", t2)
Output-
ti
Q2)Write a program to input names of n students and store them in a tuple.
Also, input a name from the user and nd if this student is present in the
tuple or not.
Ans-
lst = []
n = int(input("How many students?"))
for i in range(1, n + 1):
name = input("Enter name of student " + str(i) + " : ")
[Link](name)
ntuple = tuple(lst) # tuple created
nm = input("Enter name to be searched for : ")
if nm in ntuple:
print(nm, "exists in the tuple")
else:
print(nm, "does not exist in the tuple”)
Output-
fi
Q3)Write a program to check if the elements in the rst half of a tuple are
sorted in ascending order or not.
Ans-
tup = eval(input("Enter a tuple : "))
ln = len(tup)
mid = ln // 2
if ln % 2 == 1 :
mid = mid + 1
half = tup[:mid]
if sorted(half) == list(tup[:mid]) :
print("First half is sorted")
else :
print("First half is not sorted”)
Output-
fi