0% found this document useful (0 votes)
17 views36 pages

St. Paul'S P.U.College of Science & Commerce

The document is a certificate template from St. Paul's P.U. College of Science & Commerce for students who have completed practical work in Computer Science. It includes a list of programming tasks and algorithms for various Python programs that students are expected to complete during the academic year 2024-2025. Each program covers fundamental programming concepts such as arithmetic operations, conditionals, loops, and data structures.

Uploaded by

Simran Shaikh
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)
17 views36 pages

St. Paul'S P.U.College of Science & Commerce

The document is a certificate template from St. Paul's P.U. College of Science & Commerce for students who have completed practical work in Computer Science. It includes a list of programming tasks and algorithms for various Python programs that students are expected to complete during the academic year 2024-2025. Each program covers fundamental programming concepts such as arithmetic operations, conditionals, loops, and data structures.

Uploaded by

Simran Shaikh
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/ 36

ST. PAUL’S P.U.

COLLEGE OF
SCIENCE & COMMERCE
( CO-EDUCATION )
CAMP -BELAGAVI

Computer Science
Certificate

This is to certify that Shri / Kum


______________________________________________
of Class_______________Roll-No_____________
has satisfactorily carried out the pratical work in
Computer Science prescribed by Karnataka Board of
PUC -I, in our Laboratory and that is his/her bonafide work
during the year 2024-2025

Examiner
Internal:_______________________
External:_______________________

Signature of the Lecturer Principal Date:

…………………..
CONTENTS
Prog Date Sign
No ProgramName
PART-A
01 19/7/24 Write a program to swap two numbers using a third variable.
02 8/7/24 Write a program to enter two integers and perform all arithmetic
operations on them.
03 8/7/24 Write a Python program to accept length and width of a rectangle
and compute its perimeter and area.

04 14/8/24 Write a Python program to calculate the amount payable if money


has been lent on simple interest. Principal or money lent = P, Rate
of interest = R% per annum and Time = T years. Then Simple
Interest (SI) = (P x R x T)/ 100. Amount payable = Principal + SI.
P, R and T are given as input to the program

05 14/8/24 Write a Python program to find largest among three numbers.


Write a program that takes the name and age of the user as input
22/8/24 and displays a message whether the user is eligible to apply for a
06 driving license or not. (the eligible age is 18 years)
29/8/24 Write a program that prints minimum and maximum of five
07 numbers entered by the user.

08 6/9/24 Write a program to find the grade of a student when grades are
allocated as given in the table below.
Percentage Of Grade
marks
Above 90% A
80% to 90% B
70% to 80% C
60% to 70% D
50% to 60% E

Percentage of the marks obtained by the student is input to the


program.
09 14/9/24 Write a function to print the table of a given number. The number
has to be entered by the user

10 14/9/24 Write a program to find the sum of digits of an integer number,


input by the user.
11 20/9/24 Write a program to check whether an input number is a
palindrome or not
Write a program to print the following patterns:
12 26/9/24 1 2 3 4 5
1234
123
12
1
PART– B
Write a program that uses a user defined function that accepts
13 18/10/24 name and gender (as M for Male, F for Female) and prefixes
Mr./Ms. based on the gender.
14 25/10/24 Write a program that has a user defined function to accept the
coefficients of a quadratic equation in variables and calculates its
discriminant. For example : if the coefficients are stored in the
variables a, b, c then calculate discriminant as b2-4ac. .Write the
appropriate condition to check discriminant on positive, zero and
negative and output appropriate result.
15 4/11/24 Write a program that has a user defined function to accept 2
numbers as parameters, if number 1 is less than number 2 then
numbers are swapped and returned, i.e., number 2 is returned in
place of number1 and number 1 is reformed in place of number 2,
otherwise the same order is returned.
16 5/11/24 Write a program to input line(s) of text from the user until enter is
pressed. Count the total number of characters in the text
(including white spaces), total number of alphabets, total number
of digits, total number of special symbols and total number of
words in the given text. (Assume that each word is separated by
one space).
17 13/11/24 Write a user defined function to convert a string with more than
one word into title case string where string is passed as parameter.
(Title case means that the first letter of each word is capitalized)
18 20/11/24 Write a function that takes a sentence as an input parameter where
each word in the sentence is separated by a space. The function
should replace each blank with a hyphen and then return the
modified sentence.
19 25/11/24 Write a program to find the number of times an element occurs in
the list
20 25/11/24 Write a function that returns the largest element of the list passed
as parameter
21 28/11/24 Write a program to read a list of elements. Modify this list so that
it does not contain any duplicate elements, i.e., all elements
occurring multiple times in the list should appear only once
22 9/12/24 Write a program to read email IDs of n number of students and
store them in a tuple. Create two new tuples, one to store only the
usernames from the email IDs and second to store domain names
from the email IDs. Print all three tuples at the end of the
program. [Hint: You may use the function split()]
23 16/12/24 Write a program to input names of n students and store them in a
tuple. Also, input a name from the user and find if this student is
present in the tuple or not.
24 20/12/24 Write a Python program to create a dictionary from a string. Note:
Track the count of the letters from the string. Sample string : ‘2nd
pu course’ Expected output : {‘ ‘:2, ‘2’:1, ‘n’:1, ‘d’:1, ‘o’:1, ‘p’:1,
‘u’:2, ’c’:1, ‘s’:1, ‘r’:1, ‘e’:1}
OR
Create a dictionary with the roll number, name and marks of n
students in a class and display the names of students who have
marks above 75
PART - A
Python Lab

PROGRAM 1:

Write a program to swap two numbers using a third variable.


# swapping of two variables
x = int(input('Enter the first value' ))
y = int(input('Enter the second value'))

print("Values of variables before swapping")


print("Value of x:", x)
print("Value of y:", y)

# Swapping of two variables using third variable


temp = x
x=y
y = temp

print("Values of variables after swapping")

print("Value of x:", x)
print("Value of y:", y)

OUTPUT:
Enter the first value 34
Enter the second value 65
Values of variables before swapping
Value of x: 34
Value of y: 65
Values of variables after swapping
Value of x: 65
Value of y: 34

ALGORITHM:
Step 1: Read two numbers into variables x and y.
Step 2: Store the value of x in a temporary variable temp.
Step 3: Assign the value of y to x.
Step 4: Assign the value of temp (original x) to y.
Step 5: Display the swapped values of x and y.
Step 6: Stop.
Python Lab

PROGRAM 2:

Write a program to enter two integers and perform all arithmetic


operations on them.

#Program to input two numbers and performing all arithmetic operations


num1 = int(input("Enter first number: "))

num2 = int(input("Enter second number: "))

print("Printing the result for all arithmetic operations:- ")

print("Addition: ",num1+num2)

print("Subtraction: ",num1-num2)

print("Multiplication: ",num1*num2)

print("Division: ",num1/num2)

print("Modulus: ", num1%num2)

OUTPUT:
Enter first number: 34
Enter second number: 66
Printing the result for all arithmetic operations:-
Addition: 100
Subtraction: -32
Multiplication: 2244
Division: 0.5151515151515151
Modulus: 34

ALGORITHM:
Step 1: Start.
Step 2: Input the first number num1
Step 3: Input the second number num2.
Step 4: Perform num1+num2 and display the result.
Step 5: Perform num1-num2 and display the result.
Step 6: Perform num1*num2 and display the result.
Step 7: Perform num1/num2 and display the result.
Step 8: Perform num1%num2 and display the result.
Step 9: Stop.
Python Lab

PROGRAM 3:

Write a Python program to accept length and width of a rectangle


and compute its perimeter and area.
#Program to input length and width of rectangle and compute its perimeter and area.

length = int(input("Enter length: "))

width = int(input("Enter width: "))

area = length * width

print(‘AREA=’, area)

perim = 2 * (length + width)

print(‘PERIMETER=’, perim)

OUTPUT
Enter length: 4
Enter width: 5
AREA=20
PERIMETER=18

ALGORITHM:
Step 1: Read the length and width of the rectangle in length and width.
Step 2: Calculate the area using the formula area = length * width.
Step 3: Display the area.
Step 4: Calculate the perimeter using the formula perimeter = 2 * (length + width).
Step 5: Display the perimeter.
Step 6: Stop.
Python Lab

PROGRAM 4:

Write a Python program to calculate the amount payable if money


has been lent on simple interest. Principal or money lent = P, Rate of
interest = R% per annum and Time = T years. Then Simple Interest
(SI) = (P x R x T)/ 100. Amount payable = Principal + SI. P, R and T
are given as input to the program

#Program to input principle , rate, time and compute simple interest


P = float(input("Enter principle amount: "))

R =float(input("Enter rate: "))

T = float(input("Enter time: "))

SI=(P*R*T)/100

print('PRINCIPLE AMOUNT=', P)
print('RATE OF INTEREST=', R)
print('TIME=', T)

print('SIMPLE INTEREST=', SI)


AMOUNT=P+SI
print('AMOUNT PAYABLE=', AMOUNT)

OUTPUT
Enter principle amount: 10000.00
Enter rate: 2.5
Enter time:1.0
PRINCIPLE AMOUNT=10000.00
RATE OF INTEREST=2.5
TIME=1.0
SIMPLE INTEREST= 250.00
AMOUNT PAYABLE=10250.00

ALGORITHM
Step 1: Read the principal amount into P.
Step 2: Read the rate of interest into R.
Step 3: Read the time in years into T.
Step 4: Calculate the Simple Interest (SI) using the formula SI = (P * R * T) / 100.
Step 5: Display the principal amount P, rate of interest R, and time T.
Step 6: Display the calculated simple interest SI.
Step 7: Calculate the total amount payable as AMOUNT = P + SI.
Step 8: Display the total amount payable AMOUNT.
Step 9: Stop.
Python Lab

PROGRAM 5:

Write a Python program to find largest among three numbers.


a=int(input("enter first number:"))
b=int(input("enter second number:"))
c=int(input("enter third number:"))
if(a>b):
if(a>c):
print(a,"is the largest")
else:
print(c,"is the largest")
else:
if(b>c):
print(b,"is the largest")
else:
print(c,"is the largest")

OUPUT
enter first number:12
enter second number:18
enter third number:11
18 is the largest

ALGORITHM
Step 1: Read the first number into a.
Step 2: Read the second number into b.
Step 3: Read the third number into c.
Step 4: If a > b, then go to Step 5; otherwise, go to Step 7.
Step 5: If a > c, display a is the largest; otherwise, display c is the largest.
Step 6: Stop.
Step 7: If b > c, display b is the largest; otherwise, display c is the largest.
Step 8: Stop.
Python Lab

PROGRAM 6:

Write a program that takes the name and age of the user as input
and displays a message whether the user is eligible to apply for a
driving license or not. (the eligible age is 18 years).

input("enter name:")
x=int(input("enter age:"))
if(x>=18):
print(“eligible for license”)
else:
print(“ not eligible for license")

OUPUT
enter name:naresh
enter age:23
23 eligible for license
enter name:aarya
enter age:4
4 not eligible for license

ALGORITHM:

Step 1: Read the name of the person.


Step 2: Read the age of the person into x.
Step 3: Check if x >= 18.
Step 4: If x >= 18, display "eligible for license".
Step 5: If x < 18, display "not eligible for license".
Step 6: Stop..
Python Lab

PROGRAM 7:

Write a program that prints minimum and maximum of five


numbers entered by the user.
minimum=0
maximum=0
for a in range(0,5):
x=int(input("enter the number:"))
if a==0:
minimum=maximum=x
if(x<minimum):
minimum=x
if(x>maximum):
maximum=x
print("the minimum number is",minimum)
print("the maximum number is",maximum)

OUPUT
enter the number:10
enter the number:11
enter the number:5
enter the number:3
enter the number:2
the minimum number is 2
the maximum number is 11

ALGORITHM:
Step 1: Initialize minimum = 0 and maximum = 0.
Step 2: Start a loop for a in the range 0 to 4.
Step 3: Read a number into x.
Step 4: If a == 0, set minimum = x and maximum = x.
Step 5: If x < minimum, set minimum = x.
Step 6: If x > maximum, set maximum = x.
Step 7: End the loop after 5 iterations.
Step 8: Display the minimum number.
Step 9: Display the maximum number.
Step 10: Stop.
Python Lab

PROGRAM 8:

Write a program to find the grade of a student when grades are


allocated as given in the table below.
Percentage of Marks Grade
Grade
Above 90% A
80% to 90% B
70% to 80% C
60% to 70% D
Below 60% E
Percentage of the marks obtained by the student is input to the
program.

sub1=int(input("enter marks of the first subject: "))

sub2=int(input("enter marks of the second subject: "))

sub3=int(input("enter marks of the third subject: "))

sub4=int(input("enter marks of the fourth subject: "))

sub5=int(input("enter marks of the fifth subject: "))

sub6=int(input("enter marks of the sixth subject: "))

total=(sub1+sub2+sub3+sub4+sub5+sub6)
print("TOTAL=",total)

perc=total/6
print("PERCENTAGE=",perc)

if(perc>=90):
print("Grade: A")

elif(perc>=80 and perc<90):


print("Grade: B")

elif(perc>=70 and perc<80):


print("Grade: C")

elif(perc>=60 and perc<70):


print("Grade: D")

else:
print("Grade: E")
Python Lab

OUPUT
enter marks of the first subject: 45
enter marks of the second subject: 55
enter marks of the third subject: 65
enter marks of the fourth subject: 75
enter marks of the fifth subject: 85
enter marks of the sixth subject: 95
TOTAL= 420
PERCENTAGE= 70.0
Grade: C

ALGORITHM

Step 1: Read marks of six subjects into sub1, sub2, sub3, sub4, sub5, and sub6.
Step 2: Calculate the total marks as total = sub1 + sub2 + sub3 + sub4 + sub5 + sub6.
Step 3: Display the total marks.
Step 4: Calculate the percentage as perc = total / 6.
Step 5: Display the percentage.
Step 6: If perc >= 90, display "Grade: A".
Step 7: Else if perc >= 80, display "Grade: B".
Step 8: Else if perc >= 70, display "Grade: C".
Step 9: Else if perc >= 60, display "Grade: D".
Step 10: Else, display "Grade: E".
Step 11: Stop.
Python Lab

PROGRAM 9:

Write a function to print the table of a given number. The number


has to be entered by the
user.
n=int(input("enter number to print the tables:"))
for i in range(1,11):
print(n,"x",i,"=",n*i)

OUTPUT
enter number to print the tables:4
4x1=4
4x2=8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40

ALGORITHM

Step 1: Read a number into n.


Step 2: Start a loop with i ranging from 1 to 10.
Step 3: Calculate the product of n and i as n * i.
Step 4: Display the result in the format n x i = product.
Step 5: Repeat Steps 3 and 4 for all values of i.
Step 6: Stop.
Python Lab

PROGRAM 10:

Write a program to find the sum of digits of an integer number,


input by the user.
num=input("enter number:")
sum=0
for i in num:
sum=sum+int(i)
print(sum)

OUTPUT
enter number:123456
21

ALGORITHM

Step 1: Read a number into num.


Step 2: Initialize sum = 0.
Step 3: For each digit in num, add it to sum.
Step 4: Display the value of sum.
Step 5: Stop.
Python Lab

PROGRAM 11 :

Write a program to check whether an input number is a palindrome


or not.

n=int(input("enter number:"))
temp=n
rev=0
while(n>0):
digit=n%10
rev=rev*10+digit
n=n//10
if(temp==rev):
print("the number is a palindrome!")
else:
print("the number is not a palindrome!")

OUTPUT 1
enter number:1234
the number is not a palindrome!

OUTPUT 2
enter number:1221
the number is a palindrome!

ALGORITHM

Step 1: Read a number into n and store it in temp.


Step 2: Initialize rev = 0.
Step 3: Extract the last digit of n using digit = n % 10.
Step 4: Update rev as rev = rev * 10 + digit.
Step 5: Remove the last digit of n using n = n // 10.
Step 6: Repeat Steps 3 to 5 until n > 0.
Step 7: Compare temp with rev.
Step 8: If temp == rev, display "The number is a palindrome!".
Step 9: Otherwise, display "The number is not a palindrome!".
Step 10: Stop.
Python Lab

PROGRAM 12 :

Write a program to print the following patterns:


12345
1234
123
12
1

n=5
for i in range(n,0,-1):
for j in range(1,i+1):
print(j,end="")
print("\r")

OUTPUT

12345
1234
123
12
1

ALGORITHM
Step 1: Initialize n = 5.
Step 2: Loop i from n to 1.
Step 3: For each i, loop j from 1 to i.
Step 4: Print j with space.
Step 5: Move to the next line after each inner loop.
Step 6: Stop.
Python Lab

PART - B
Python Lab

PROGRAM 13:

Write a program that uses a user defined function that accepts name
and gender (as M for Male, F for Female) and prefixes Mr./Ms.
based on the gender.

# defining a function which takes name and gender as input


def prefix(name,gender):
if(gender=='M' or gender=='m'):
print("Hello, Mr.",name)
elif(gender=='F' or gender=='f'):
print("Hello, Ms.",name)
else:
print("Please enter only M or F in gender")
#asking the user to enter the name
name=input("enetr your name:")
#asking the user to enter the gender a M/F
gender=input("enter your gender: M for Male, and F for female:")
#calling function
prefix(name,gender)

OUTPUT 1
enetr your name:naresh
enter your gender: M for Male, and F for female: M
Hello, Mr. naresh
OUTPUT 2
enetr your name:aarya
enter your gender: M for Male, and F for female: f
Hello, Ms. Aarya
OUTPUT 3
enetr your name:xyz
enter your gender: M for Male, and F for female:b
Please enter only M or F in gender

ALGORITHM

Step 1: Define a function prefix(name, gender).


Step 2: If gender == 'M' or gender == 'm', print "Hello, Mr. name".
Step 3: Else if gender == 'F' or gender == 'f', print "Hello, Ms. name".
Step 4: Else, print "Please enter only M or F in gender".
Step 5: Read the name from the user.
Step 6: Read the gender from the user.
Step 7: Call the function prefix(name, gender).
Python Lab

Step 8: Stop.

PROGRAM 14:

Write a program that has a user defined function to accept the


coefficients of a quadratic equation in variables and calculates its
discriminant. For example : if the coefficients are stored in the
variables a, b, c then calculate discriminant as b2-4ac . .Write the
appropriate condition to check discriminant on positive, zero and
negative and output appropriate result.

import math
def equationroots(a,b,c):
#calculating discriminant using formula
disc=b*b-4*a*c
sqrt_val=math.sqrt(abs(disc))
#checking condition for discriminant
if disc>0:
print("real and different roots")
print((-b+sqrt_val)/(2*a))
print((-b-sqrt_val)/(2*a))
elif disc==0:
print("real and equal roots")
print(-b/(2*a))
print(-b/(2*a))
else:
print("complex roots")
print(-b/(2*a),”+I”,sqrt_val)
print(-b/(2*a),”-I”,sqrt_val)
a=int(input("enter first coefficient:"))
b=int(input("enter second coefficient:"))
c=int(input("enter third coefficient:"))
if a==0:
print("input correct coefficient for quadratic equation")
else:
equationroots(a,b,c)

OUTPUT 1
enter first coefficient:1
enter second coefficient:2
enter third coefficient:1
real and equal roots
-1.0
-1.0

OUTPUT 2
enter first coefficient:5
enter second coefficient:1
Python Lab

enter third coefficient:2


complex roots
-0.1 +i 6.244997998398398
-0.1 -i 6.244997998398398

OUTPUT 3
enter first coefficient:1
enter second coefficient:5
enter third coefficient:2
real and different roots
-0.4384471871911697
-4.561552812808831

OUTPUT 4
enter first coefficient:0
enter second coefficient:1
enter third coefficient:2
input correct coefficient for quadratic equation

ALGORITHM

Step 1: Import the math module.


Step 2: Define the function equationroots(a, b, c).
Step 3: Calculate the discriminant disc = b*b - 4*a*c.
Step 4: Calculate the square root of the absolute value sqrt_val = math.sqrt(abs(disc)).
Step 5: If disc > 0, print the two real and different roots.
Step 6: If disc == 0, print the real and equal root.
Step 7: If disc < 0, print the complex roots.
Step 8: Read a, b, and c from the user.
Step 9: If a == 0, print an error message.
Step 10: Otherwise, call equationroots(a, b, c).
Step 11: Stop.
Python Lab

PROGRAM 15:

Write a program that has a user defined function to accept 2


numbers as parameters, if number 1 is less than number 2 then
numbers are swapped and returned, i.e., number 2 is returned in
place of number1 and number 1 is reformed in place of number 2,
otherwise the same order is returned.
def swap(a,b):
if(a<b):
return b,a
else:
return a,b
#asking the user to provide two numbers
n1=int(input("enter number 1:"))
n2=int(input("enter number 2:"))
print("Before swapping numbers:")
print("Number 1:",n1)
print("Number 2:",n2)
print("After swapping numbers:")
n1,n2=swap(n1,n2)
print("Number 1:",n1)
print("Number 2:",n2)

OUTPUT
enter number 1:100
enter number 2:200
Before swapping numbers:
Number 1: 100
Number 2: 200
After swapping numbers:
Number 1: 200
Number 2: 100

ALGORITHM

Step 1: Define a function swap(a, b) that checks if a < b.


Step 2: If true, return b, a; otherwise, return a, b.
Step 3: Ask the user to input two numbers n1 and n2.
Step 4: Display "Before swapping numbers" along with the values of n1 and n2.
Step 5: Call the swap(n1, n2) function to swap the values and assign them back to n1
and n2.
Step 6: Display "After swapping numbers" along with the swapped values of n1 and
n2.
Step 7: Stop.
Python Lab

PROGRAM 16:

Write a program to input line(s) of text from the user until enter is
pressed. Count the total number of characters in the text (including
white spaces),total number of alphabets, total number of digits, total
number of special symbols and total number of words in the given
text. (Assume that each word is separated by one space).

userInput = input("Write a sentence: ")


totalChar = len(userInput)
print("Total Characters: ",totalChar)

#Count the total number of alphabets,digit and special characters by looping through
each character and incrementing the respective variable value
totalAlpha = totalDigit = totalSpecial = 0

for a in userInput:
if a.isalpha():
totalAlpha += 1
elif a.isdigit():
totalDigit += 1
else:
totalSpecial += 1

print("Total Alphabets: ",totalAlpha)

print("Total Digits: ",totalDigit)

print("Total Special Characters: ",totalSpecial)


#Count number of words (Assume that each word is separated by one space)
#Therefore, 1 space:2 words, 2 space:3 words and so on

totalSpace = 0
for b in userInput:
if b.isspace():
totalSpace += 1
print("Total Words in the Input :",(totalSpace + 1))

OUTPUT 1
Write a sentence: HEY ARE YOU
Total Characters: 11
Total Alphabets: 9
Total Digits: 0
Total Special Characters: 2
Total Words in the Input : 3
Python Lab

OUTPUT2
Write a sentence: COMPUTER SCIENCE PUC-1
Total Characters: 22
Total Alphabets: 18
Total Digits: 1
Total Special Characters: 3
Total Words in the Input : 3

ALGORITHM
Step 1: INPUT a sentence in userInput.
Step 2: SET totalAlpha = 0, totalDigit = 0, totalSpecial = 0, totalSpace = 0.
Step 3: CALCULATE totalChar = len(userInput) and PRINT it.
Step 4: FOR each character in userInput:
IF alphabet, INCREMENT totalAlpha.
ELSE IF digit, INCREMENT totalDigit.
ELSE IF space, INCREMENT totalSpace.
ELSE, INCREMENT totalSpecial.
Step 5: PRINT totalAlpha, totalDigit, totalSpecial.
Step 6: CALCULATE total words as totalSpace + 1 and PRINT it.
Step 7: STOP.
Python Lab

PROGRAM17:

Write a user defined function to convert a string with more than one
word into title case string where string is passed as parameter. (Title
case means that the first letter of each word is capitalised)

def convertToTitle(string):
titleString = string.title()
print('The input string in title case is:',titleString)
userInput = input("Write a sentence: ")
#Counting the number of space to get the number of words
totalSpace = 0
for b in userInput:
if b.isspace():
totalSpace += 1
#If the string is already in title case
if(userInput.istitle()):
print("The String is already in title case")
#If the string is not in title case and consists of more than one word
elif(totalSpace > 0):
convertToTitle(userInput)
#If the string is of one word only
else:
print("The String is of one word only")

OUTPUT 1
Write a sentence: good evening!
The input string in title case is: Good Evening!

OUTPUT 2
Write a sentence: Good Morning
The String is already in title case

OUTPUT 3
Write a sentence: science
The String is of one word only

ALGORITHM
Step 1: INPUT a string in userInput.
Step 2: SET totalSpace = 0.
Step 3: FOR each character in userInput, IF it is a space, INCREMENT totalSpace.
Step 4: IF the string is already in title case
PRINT
Step 5: ELSE IF totalSpace > 0
PRINT the result.
Step 6: ELSE
PRINT "The String is of one word only".
Python Lab

Step 7: STOP.

PROGRAM 18:

Write a function that takes a sentence as an input parameter where


each word in the sentence is separated by a space. The function
should replace each blank with a hyphen and then return the
modified sentence.

#replaceChar function to replace space with hyphen


def replaceChar(string):
return string.replace(' ','-')
userInput = input("Enter a sentence: ")
#Calling the replaceChar function to replace space with hyphen
result = replaceChar(userInput)
#Printing the modified sentence
print("The new sentence is:",result)

OUTPUT
Enter a sentence: WELCOME TO THE WORLD OF COMPUTERS
The new sentence is: WELCOME-TO-THE-WORLD-OF-COMPUTERS

ALGORITHM
Step 1: INPUT a sentence
Step 2: REPLACE spaces and STORE the result in RESULT.
Step 3: PRINT AND store in RESULT.
Step 4: STOP.
Python Lab

PROGRAM 19:

Write a program to find the number of times an element occurs in the list.
#defining a list
list1 = [10, 20, 30, 40, 50, 60, 20, 50, 10, 30, 50, 30, 24, 45]
#printing the list for the user
print("The list is:",list1)
#asking the element to count
inp = int(input("Which element occurrence would you like to count? "))
#using the count function
count = list1.count(inp)
#printing the output
print("The count of element",inp,"in the list is:",count)

OUTPUT 1
The list is: [10, 20, 30, 40, 50, 60, 20, 50, 10, 30, 50, 30, 24, 45]
which element occurrence would you like to count?
10 The count of element 10 in the list is: 2

OUTPUT 2
The list is: [10, 20, 30, 40, 50, 60, 20, 50, 10, 30, 50, 30, 24, 45]
Which element occurrence would you like to count?
50 The count of element 50 in the list is: 3

ALGORITHM
Step 1: DEFINE a list list1 with elements.
Step 2: PRINT the list
Step 3: INPUT the element to count and store in inp.
Step 4: USE the count function to find the occurrences of inp in list1 and STORE the
result in count.
Step 5: PRINT the count of the element.
Step 6: STOP.
Python Lab

PROGRAM 20:

Write a function that returns the largest element of the list passed as
parameter using max() function of the list.

#Using max() function to find largest number


def largestNum(list1):
l = max(list1)
return l
list1 = [10, 20, 30, 40, 50, 60, 20, 50, 10, 30, 50, 30, 24, 45]
#Using largestNum function to get the function
max_num = largestNum(list1)
#Printing all the elements for the list
print("The elements of the list",list1)
#Printing the largest num
print("\nThe largest number of the list:",max_num)

OUTPUT
The elements of the list [10, 20, 30, 40, 50, 60, 20, 50, 10, 30, 50, 30, 24, 45]
The largest number of the list: 60

ALGORITHM
Step 1: DEFINE list list1 with elements.
Step 2: PRINT the elements of the list.
Step 3: FIND the largest number in the list using the max() function and STORE it in
max_num.
Step 4: PRINT the largest max_num.
Step 5: STOP.
Python Lab

PROGRAM 21:

Write a program to read a list of elements. Modify this list so that it


does not contain any duplicate elements, i.e., all elements occurring
multiple times in the list should appear only once.

def removeDup(list1):
length = len(list1)
newList = []
for a in range(length):
#Checking if an element is not in the new List .This will reject duplicate values
if list1[a] not in newList:
newList.append(list1[a])
return newList
list1 = []
#Asking for number of elements to be added in the list
inp = int(input("How many elements do you want to add in the list? "))
#Taking the input from user
for i in range(inp):
a = int(input("Enter the elements: "))
list1.append(a)
print("The list entered is:",list1)
print("The list without any duplicate element is:",removeDup(list1))

OUTPUT
How many elements do you want to add in the list? 8
Enter the elements: 1
Enter the elements: 2
Enter the elements: 1
Enter the elements: 3
Enter the elements: 4
Enter the elements: 3
nter the elements: 5
Enter the elements: 6
The list entered is: [1, 2, 1, 3, 4, 3, 5, 6]
The list without any duplicate element is: [1, 2, 3, 4, 5, 6]

ALGORITHM
Step 1: INPUT the number of elements to add in the list as inp.
Step 2: FOR i from 0 to inp - 1, REPEAT steps 3 and 4.Step 3: INPUT an element a.
Step 4: APPEND a to list1.
Step 5: PRINT the list list1.
Step 6: SET newList to an empty list.
Step 7: FOR each element in list1, IF the element is NOT in newList, APPEND it to
newList.
Python Lab

Step 8: PRINT newList as the list without duplicates.


Step 9: STOP.
PROGRAM 22:

Write a program to read email IDs of n number of students and store


them in a tuple. Create two new tuples, one to store only the
usernames from the email IDs and second to store domain names
from the email IDs. Print all three tuples at the end of the program.
[Hint: You may use the function split()]

emails = tuple()
username = tuple()
domainname = tuple()

#Create empty tuple 'emails', 'username' and domain-name


n = int(input("How many email ids you want to enter?: "))
for i in range(0,n):
emid = input(">")

#It will assign emailid entered by user to tuple 'emails'


emails = emails +(emid,)

#This will split the email id into two parts, username and domain and return a list
spl = emid.split("@")

#assigning returned list first part to username and second part to domain name
username = username + (spl[0],)
domainname = domainname + (spl[1],)

print("\nThe email ids in the tuple are:")

#Printing the list with the email ids


print(emails)
print("\nThe username in the email ids are:")

#Printing the list with the usernames only


print(username)
print("\nThe domain name in the email ids are:")

#Printing the list with the domain names only


print(domainname)

OUTPUT-
How many email ids you want to enter?: 3
> [email protected]
> [email protected]
> [email protected]
The email ids in the tuple are:
Python Lab

(' [email protected]', '[email protected]', '[email protected]')


The username in the email ids are:
(' abcde', 'test1', 'testing')
The domain name in the email ids are:
('gmail.com', 'meritnation.com', 'outlook.com')

ALGORITHM
Step 1: INPUT the number of email IDs n.
Step 2: INITIALIZE three empty tuples: emails, username, and domain name.
Step 3: FOR i from 0 to n-1, REPEAT steps 4 to 7.
Step 4: INPUT an email ID emid.
Step 5: APPEND emid to the emails tuple.
Step 6: SPLIT emid into two parts using @ and STORE the first part in username and
the second part in domain name.
Step 7: APPEND the username part to the username tuple and the domain name part
to the domain name tuple.
Step 8: PRINT the emails tuple.
Step 9: PRINT the username tuple.
Step 10: PRINT the domain name tuple.
Step 11: STOP.
Python Lab

PROGRAM 23:

Write a program to input names of n students and store them in a


tuple. Also, input a name from the user and find if this student is
present in the tuple or not.

name = tuple()
#Create empty tuple 'name' to store the values
n = int(input("How many names do you want to enter?: "))

for i in range(0, n):


num = input(">")

#it will assign name entered by user to tuple 'name'


name = name + (num,)
print("\nThe names entered in the tuple are:")
print(name)

search=input("\nEnter the name of the student you want to search? ")

#Using membership function to check if name is present or not

if search in name:
print("The name",search,"is present in the tuple")
else:
print("The name",search,"is not found in the tuple")

OUTPUT1
How many names do you want to enter?: 3
> naresh
> akash
> priya
The names entered in the tuple are:
('naresh', 'akash', 'priya')
Enter the name of the student you want to search? priya
The name priya is present in the tuple

OUTPUT2
How many names do you want to enter?: 3
> naresh
> akash
> priya
The names entered in the tuple are:
('naresh', 'akash', 'priya')
Enter the name of the student you want to search? vidhan
Python Lab

The name vidhan is not found in the tuple

ALGORITHM
Step 1: INPUT the number of names n.
Step 2: INITIALIZE an empty tuple name.
Step 3: FOR i from 0 to n-1, REPEAT steps 4 and 5.
Step 4: INPUT a name num.
Step 5: APPEND num to the name tuple.
Step 6: PRINT the name tuple.
Step 7: INPUT the name to search as search.
Step 8: IF search is present in the name tuple, PRINT that the name is present.
Step 9: ELSE, PRINT that the name is not found.
Step 10: STOP.
Python Lab

PROGRAM 24:

Write a Python program to create a dictionary from a string. Note:


Track the count of the letters from the string. Sample string : ‘2nd pu
course’ Expected output : {‘ ‘:2, ‘2’:1, ‘n’:1, ‘d’:1, ‘o’:1, ‘p’:1, ‘u’:2,
’c’:1, ‘s’:1, ‘r’:1, ‘e’:1}
OR
Create a dictionary with the roll number, name and marks of n
students in a class and display the names of students who have marks
above 75

myStr=input("The input string is:")


myDict=dict()

for character in myStr:

if character in myDict:
myDict[character]+=1
else:
myDict[character]=1

print("The dictionary created from characters of the string is:")


print(myDict)

OUTPUT
The input string is: "welcome to cs department"
The dictionary created from characters of the string is:
{'"': 2, 'w': 1, 'e': 4, 'l': 1, 'c': 2, 'o': 2, 'm': 2, ' ': 3, 't': 3, 's': 1, 'd': 1, 'p': 1, 'a': 1, 'r': 1, 'n':
1}

ALGORITHM
Step 1: INPUT a string myStr.
Step 2: INITIALIZE an empty dictionary myDict.
Step 3: FOR each character in myStr, REPEAT steps 4 to 6.
Step 4: IF the character is already in myDict, INCREMENT its value by 1.
Step 5: ELSE, ADD the character as a key in myDict with value 1.
Step 6: CONTINUE the loop.
Step 7: PRINT the dictionary myDict.
Step 8: STOP.
Python Lab

OR

n=int(input("Enter number of students: "))


result={}

for i in range(n):
print("Enter Details of student No.", i+1)
rno = int(input("Roll No: "))
name = input("Name: ")
marks = int(input("Marks: "))
result[rno] = [name, marks]
print(result)

# Display names of students who have got marks more than 75


for student in result:

if result[student][1] > 75:

print(result[student][0])

OUTPUT
Enter number of students: 3
Enter Details of student No. 1
Roll No: 121
Name: amit
Marks: 67
Enter Details of student No. 2
Roll No: 122
Name: sumit
Marks: 78
Enter Details of student No. 3
Roll No: 123
Name: akshay
Marks: 90
{121: ['amit', 67], 122: ['sumit', 78], 123: ['akshay', 90]}
sumit
Akshay

ALGORITHM
Step 1: INPUT n
Step 2: INITIALIZE an empty dictionary result.
Step 3: FOR each student, INPUT rno, name, and marks, and STORE in result.
Step 4: PRINT result.
Step 5: FOR each student, IF marks > 75, PRINT the name.

You might also like