0% found this document useful (0 votes)
54 views25 pages

1 Puc Computer Science Lab Recoard

The document contains a series of Python programming exercises covering various topics such as variable swapping, arithmetic operations, area and perimeter calculations, simple interest, finding the largest of three numbers, eligibility for a driving license, and more. Each exercise includes code snippets, expected outputs, and comments explaining the functionality. The exercises aim to enhance programming skills through practical applications of Python.

Uploaded by

Siddharth. K
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)
54 views25 pages

1 Puc Computer Science Lab Recoard

The document contains a series of Python programming exercises covering various topics such as variable swapping, arithmetic operations, area and perimeter calculations, simple interest, finding the largest of three numbers, eligibility for a driving license, and more. Each exercise includes code snippets, expected outputs, and comments explaining the functionality. The exercises aim to enhance programming skills through practical applications of Python.

Uploaded by

Siddharth. K
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/ 25

PART-A

1. Write a python program to interchange the values of two variables using the
third variable.

# To input two numbers


a=int(input("Enter first number: "))
b=int(input("Enter second number:”))

# To print number before swapping


print("Before interchanging")
print("value of a =", a)
print("value of b =", b)
# To interchange two numbers
temp=a
a=b
b=temp
# To print number after swapping
print("After interchanging")
print("value of a =", a)
print("value of b =", b)

**********************OUTPUT ********************
Enter first number : 20
Enter second number : 30
Before interchanging
value of a = 20
value of b = 30
After interchanging
value of a = 30
value of b = 20
**********************OUTPUT 2********************
2. Write a python program to input two numbers and perform all arithmetic
operations on them.

# To input two numbers


a=int(input("Enter first number : "))
b=int(input("Enter second number : "))
# To perform all arithmetic operations
s=a+b
d=a-b
p=a*b
q1=a/b
q2=a//b
r=a%b
print("printing the result of all arithmetic operations")
q1=a//b

print("Addition =",s)
print("Subtraction=",d)
print("Multiplication=",p)
print("Division =", q1)

print("Quotient =", q2)


print("Remainder =", r)

**********************OUTPUT 1********************
Enter first number : 20
Enter second number : 10
printing the result of all arithmetic operations
Addition = 30
Subtraction= 10
Multiplication= 200
Division = 2.0
Quotient = 2
Remainder = 0

**********************OUTPUT 2********************
3. Write a python program to input length and width and find the area and
perimeter of rectangle.

# To input two length and breadth


# l= Length, b= width/Breadth
l=float(input("Enter the length : "))
w=float(input("Enter the width : "))
# To calculate area and perimeter
area=l*w
perimeter=2*(l+w)
# To print area and perimeter
print("area of rectangle=", area)
print(" perimeter of rectangle=",perimeter)

**********************OUTPUT 1********************
Enter the length : 2.5
Enter the width : 3.5
area of rectangle= 8.75
perimeter of rectangle= 12.0

**********************OUTPUT 2********************
4. Write a python program to input principle amount P, Time T and rate of
interest R and find the simple interest .

# To input principle amount, time and rate of interest


p=int(input("Enter principle amount : "))
t=int(input("Enter time : "))
r=int(input("Enter rate of interest : "))
# To calculate simple interest and amount payable.
si=(p*t*r)/100
ap=p+si
# To print simple interest and amount payable
print("simple interest=", si)
print("amount payable=",ap)

**********************OUTPUT 1********************
Enter principle amount : 10000
Enter time : 2
Enter rate of interest : 12
simple interest= 2400.0
amount payable= 12400.0

**********************OUTPUT 2********************
5. Write a python program to find the largest of three numbers

# To input three numbers


a=int(input("Enter first number : "))
b=int(input("Enter second number : "))
c=int(input("Enter third number : "))

# To find the largest of three numbers

big=a #assume a is largest


if (b>big):
big=b
if(c>big):
big=c

# To print the largest of three numbers


print("largest of three numbers=", big)

**********************OUTPUT 1********************
Enter first number : 10
Enter second number : 30
Enter third number : 20
largest of three numbers= 30

**********************OUTPUT 2********************
6. Write a python 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).

# To input name and age


name=(input("Enter the name : "))
age=int(input("Enter the age : "))

# To check and print eligible or not eligible for


# license.
if age>=18:
print(" name=", name)
print(" He is eligible for driving license")
else :
print("name=", name)
print("He is not eligible for driving license")

**********************OUTPUT 1********************
Enter the name : xyz
Enter the age : 35
name= xyz
He is eligible for driving license.

**********************OUTPUT 2********************
7. Write a python program to find the minimum and maximum of five numbers
entered by the user.

#Program to input five numbers and print largest and smallest numbers

#Accept 5 numbers from user convert them into integers and store them in #list

numlist=[int(input("Enter the number: "))for i in range(5)]


#initialising the variables largest and smallest with the first number in list

largest=smallest=numlist[1]
#loop to verify each number in the list and find the largest and smallest number

for i in numlist:
if i<smallest:
smallest=i
if i >largest:
largest=i
print("The smallest number is", smallest)
print("The largest number is ",largest)

**********************OUTPUT
1********************
Enter the number: 20
Enter the number: 10
Enter the number: 15
Enter the number: 50
Enter the number: 30
The smallest number is 10
The largest number is 50

**********************OUTPUT
********************
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 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.

# To input percentage
perc=int(input("Enter the student percentage : "))
# To find and print the grade
if(perc>90):
print("grade= A")
elif(perc>=80 and perc<90):
print("grade= B")
elif(perc>=70 and perce<80):
print("grade= C")
elif(perc>=60 and perc<70):
print("grade= D")
else:
print("grade= E")

**********************OUTPUT
1********************
Enter the student percentage : 56
grade= E

**********************OUTPUT 2********************
9. Write a function to print the table of a given number. The number has to
be entered by the user.

# To input number
number = int(input ("Enter the number print the multiplication table:"))

# To print the table of given number


print ("The Multiplication Table of: ", number)
for count in range(1, 11):
print (number, 'x', count, '=', number * count)

**********************OUTPUT 1********************
Enter the number print the multiplication table: 7
The Multiplication Table of: 7
7x1=7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
10. Write a program to find the sum of digits of an integer number, input by the
user.

# To input number
num=int(input("Enter number"))
# To initialize sum value
sum = 0
# To find sum of digits and print the result
while (num != 0):
r = num % 10
sum = sum + r
num = num // 10
print(sum)

**********************OUTPUT 1********************
Enter the digit : 456
15

**********************OUTPUT 2********************
11. Write a program to check whether an input number is a palindrome or not.

# To input number
num=int(input("Enter number:"))
# To initialize temp and rev
temp=num
rev=0
# To find the given number is palindrome or not
while(num>0):
dig=num%10
rev=rev*10+dig
num=num//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")

********************OUTPUT 1********************
Enter number: 6226
The number is a palindrome!

**********************OUTPUT 2********************
12. Write a program to print the following patterns:

12345
1234
123
12
1

# To specify total rows


rows = 5

# To specify downward pattern where numbers get reduced in each


# iteration and on the last row its shows only one number. Use of
# reverse for loop to print this pattern.
for i in range(rows,0, -1):
for j in range(1, i + 1): print(j, end=’ ‘)
print(‘\r’)

**********************OUTPUT 1********************

12345
1234
123
12
1
PART-B
13. Write a program to that uses a user defined function that accepts name and
gender (as M for male and F for female) and prefixes Mr./Mrs. 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("Enter your name: ")

#Asking the user to enter the gender as M/F


gender = input("Enter your gender: M for Male, and F for Female: ")

#calling the function


prefix(name,gender)

**********************OUTPUT 1********************
Enter your name: Manoj
Enter your gender: M for Male, and F for Female: M
Hello, Mr. Manoj

**********************OUTPUT 2********************
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.

#defining the function which will calculate the discriminant

def discriminant(a, b, c):


w = y**2 - 4 * x * z
return w

#asking the user to provide values of a, b, and c

print("For a quadratic equation in the form of ax^2 + bx + c = 0")


a = int(input("Enter the value of a: "))
b = int(input("Enter the value of b: "))
c = int(input("Enter the value of c: "))

#Calling the function to get the discriminant

det = discriminant(a,b,c)

#Printing the result based on the discriminant value

if (det > 0):


print("The quadratic equation has two real roots.")
elif (det == 0):
print("The quadratic equation has two equal real roots.")
else:
print("The quadratic equation has no real root.")

*******************************OUTPUT 1*********************
# For a quadratic equation in the form of
# ax^2 + bx + c = 0
Enter the value of a: 2
Enter the value of b: 6
Enter the value of c: 3
The quadratic equation has two real roots.

*******************************OUTPUT 2*********************
For a quadratic equation in the form of ax^2 + bx + c = 0
Enter the value of a: 2
Enter the value of b: 3
Enter the value of c: 4
The quadratic equation doesn't have any real root.
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.

#defining a function to swap the numbers


def swapN(a, b):
t=a
a=b
b=t
return a,b

#asking the user to provide two numbers


n1 = int(input("Enter Number 1: "))
n2 = int(input("Enter Number 2: "))
print("Values sent to the function:")
print("Number 1:",n1," Number 2: ",n2)
print("Returned value from function:")

#calling the function to get the returned value


n1, n2 = swapN(n1, n2)
print("Number 1:",n1," Number 2: ",n2)

********************************OUTPUT 1***************
Enter Number 1: 2
Enter Number 2: 4
Returned value from function:
Number 1: 4 Number 2: 2

********************************OUTPUT 2*********************
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: ")

#Count the total number of characters in the text (including white


#spaces)which is the length of string
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: Computer science!
Total Characters: 17
Total Alphabets: 15
Total Digits: 0
Total Special Characters: 2
Total Words in the Input : 2

*************************OUTPUT 2***************
17. 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)

#Changing a string to title case using title() function


def titlecase(string):
print(str.title())

#accept an input string


str = input("Write a sentence: ")
titlecase(str)

*******************OUTPUT 1************
Write a sentence: computer science is a best subject
Computer Science Is A Best Subject

*******************OUTPUT 2************
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.

#Changing a blank space into hypen in a string using replace()


#function
def hypen(string):
print(str.replace(' ','-'))

#accept an input string


str = input("Write a sentence: ")
hypen(str)

**************************OUTPUT 1***********
Write a sentence: Bangalore east west
Bangalore-east-west

**************************OUTPUT 2***********
19. 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.

#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? 30
The count of element 30 in the list is: 3

**************************OUTPUT 2***********
20. Write a function that returns the largest element of the list passed as
parameter.

#Using max() function to find largest number


def largestNum(list1):
l = max(list1)
return l
list1 = [1, 2, 3, 14, 5, 6, 7, 8, 9]

#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 1***********
The elements of the list [1, 2, 3, 14, 5, 6, 7, 8, 9]

The largest number of the list: 14

**************************OUTPUT 2***********
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.

# To enter number of elements in list


n=int(input("Enter the number elements"))
l=[ ]

# To enter the elements into the list


for i in range(n):
ele=input("Enter the elements")
l.append(ele)

# To print the list with duplicate elements


print("my list",i)

# To remove the duplicate elements and print the list


non_duplicate_value=set(l)
print("list after removing duplicate elements is")
print(non_duplicate_value)

**************************OUTPUT 1***********
Enter the number elements4
Enter the elements10
Enter the elements20
Enter the elements20
Enter the elements10
my list ['10', '20', '20', '10']
list after removing duplicate elements is {'20', '10'}
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()]

#To enter number of students


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

#To enter email id’s of students


for i in range(n):
email=input("Enter email: ")
list1.append(email)
tuple1=tuple(list1)
names=[]
domains=[]
for i in tuple1:
name,domain = i.split("@")
names.append(name)
domains.append(domain)
names = tuple(names)
domains = tuple(domains)
print("Names = ",names)
print("Domains = ",domains)
print("Tuple = ",tuple1)

**************************OUTPUT 1***********
Enter number of students : 2 Enter email: [email protected]
Enter email: [email protected] Names =
('pguru319', 'gurucs012') Domains =
('gmail.com', 'gmail.com')
Tuple = ('[email protected]', '[email protected]')

**************************OUTPUT 2***********
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.

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


list1 = []
for i in range(n):
name = input()
list1.append(name)
# makes a tuple from the list of names
# tuple1 = tuple(list1)
findName = input("Enter name to find: ")

# a user defined function to search


def userDefinedSearch():
cnt=0
#loops through every element of tuple
for item in tuple1:
#if any element is equal to what we are finding
if item==findName:
cnt+=1

#announce item found


If cnt > 0:
print("Name found")
else
print("Name not found")
return #return from the function
#this statement is reached only if the element is not found

#calling user defined function


userDefinedSearch()

**************************OUTPUT 1***********
Enter the number of students: 3
arun
varun
dhavan
Enter name to find: dhavan
Name found

**************************OUTPUT 2***********
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}

st = input("Enter a string: ")


dic = {} #creates an empty dictionary
for ch in st:
if ch in dic: #if next character is already in the dictionary
dic[ch] += 1
else:
dic[ch] = 1 #if ch appears for the first time
for key in dic:
print(’’’,key,’’’,':',dic[key])

**********************OUTPUT 1************************
enter a string: 1puc cs
1:1
p:1
u:1
c:2
:1
s:1
**********************OUTPUT 2************************
24.B) 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.

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


result = {}
for i in range(no_of_std):
print("Enter Details of student No.", i+1)
roll_no = int(input("Roll No: "))
std_name = input("Student Name: ")
marks = int(input("Marks: "))
result[roll_no] = [std_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("Student's name who get more than 75 marks is/are", (result[student][0]))

**********************OUTPUT 1************************
Enter number of students: 3
Enter Details of student No. 1
Roll No: 001
Student Name: guru
Marks: 76
Enter Details of student No. 2
Roll No: 002
Student Name: ramesh
Marks: 60
Enter Details of student No. 3
Roll No: 003
Student Name: prakash
Marks: 85
{1: ['guru', 76], 2: ['ramesh', 60], 3: ['prakash', 85]}
Student's name who get more than 75 marks is/are guru
Student's name who get more than 75 marks is/are prakash

**********************OUTPUT 2************************

You might also like