0% found this document useful (0 votes)
1K views34 pages

I Puc - 24 Python Programs

The document provides a list of 12 practical programs in Python. It includes programs to swap numbers, perform arithmetic operations, calculate area and perimeter of a rectangle, calculate simple interest, find the largest among three numbers, check eligibility for driving license, find minimum and maximum of five numbers, find grade based on percentage, print a number table, find sum of digits, check palindrome and print patterns.

Uploaded by

BHARGAVI SHETTY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views34 pages

I Puc - 24 Python Programs

The document provides a list of 12 practical programs in Python. It includes programs to swap numbers, perform arithmetic operations, calculate area and perimeter of a rectangle, calculate simple interest, find the largest among three numbers, check eligibility for driving license, find minimum and maximum of five numbers, find grade based on percentage, print a number table, find sum of digits, check palindrome and print patterns.

Uploaded by

BHARGAVI SHETTY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

I PUC – Computer Science

List of Practical Programs


CHAPTER 5 : GETTING STARTED
WITH PYTHON
A1) Write a program to swap two numbers
using a third variable.
x = 10
y = 50
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)
A2) Write a python 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)
A3) Write a Python program to accept length and width
of a rectangle and compute its perimeter and area.
# Reading length from user
length = float(input("Enter length of the rectangle: "))

# Reading breadth from user


breadth = float(input("Enter breadth of the rectangle: "))

# Calculating area
area = length * breadth

# Calculating perimeter
perimeter = 2 * (length * breadth)

# Displaying results
print("Area of rectangle = ", area)
print("Perimeter of rectangle = ", perimeter)
A4) 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.

# Reading principal amount, rate and time


principal = float(input('Enter amount: '))
time = float(input('Enter time: '))
rate = float(input('Enter rate: '))

# Calcualtion
simple_interest = (principal*time*rate)/100

# Displaying result
print('Simple interest is: ',simple_interest)
Chapter 6 : Flow of Control
A5) Write a Python program to find largest
among three numbers.
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number is", largest)


A6) 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).

#Program to check the eligibility for driving license


name = input("What is your name? ")
age = int(input("What is your age? "))

#Checking the age and displaying the message accordingly


if age >= 18:
print("You are eligible to apply for the driving license.")
else:
print("You are not eligible to apply for the driving license.")
A7) Write a program that prints minimum and
maximum of five numbers entered by the user.

smallest = 0
largest = 0
for a in range(0,5):
x = int(input("Enter the number: "))
if a == 0:
smallest = largest = x
if(x < smallest):
smallest = x
if(x > largest):
largest = x
print("The smallest number is",smallest)
print("The largest number is ",largest)
A8) Write a python 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.

n = float(input('Enter the percentage of the student: '))

if(n > 90):


print("Grade A")
elif(n > 80):
print("Grade B")
elif(n > 70):
print("Grade C")
elif(n >= 60):
print("Grade D")
else:
print("Grade E")
A9) Write a python program to print the table of a given number.
The number has to be entered by the user

num = int(input("Enter the number: "))


count = 1
while count <= 10:
prd = num * count
print(num, 'x', count, '=', prd)
count += 1
A10) Write a program to find the sum of digits of
an integer number, input by the user
sum = 0
#Getting user input
n = int(input("Enter the number: "))
# looping through each digit of the number, Modulo by 10 will give
the first digit and floor operator decreases the digit 1 by 1
while n > 0:
digit = n % 10
sum = sum + digit
n = n//10
# Printing the sum
print("The sum of digits of the number is",sum)
A11) Write a program to check whether an
input number is a palindrome or not.
# Taking the number 123 as n to check palindrome
n = int(input("Enter a number:"))
# Making a copy of the input number
temp = n
# Declaring a variable to store the reverse of the input number.
reverse = 0
# Reversing the number using a while loop
while(n>0):
digit = n % 10
reverse = reverse*10 + digit
n = n // 10
# Checking whether the reversed number is equal to the original number.
if(temp == reverse):
print("Palindrome")
else:
print("Not a Palindrome“)
A12) Write a python program to print the following patterns:
12345
1234
123
12
1

rows = int(input("Enter the number of rows: "))

for i in range(rows,0,-1):

for j in range(1,i+1):
#print the number from 1 to i+1
print(j, end=" ")

#print the next row in new line


print()
Part B

Chapter 7 : Functions
B1) 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 on the
basis of 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)
B2. Write a program that has a user defined function to accept the coefficients of a
quadratic equation in variables and calculates its determinant. For example : if the
coefficients are stored in the variables a,b,c then calculate determinant as b2-4ac.
Write the appropriate condition to check determinants on positive, zero and
negative and output appropriate result.

def discriminant(a, b, c):


d = b**2 - 4 * a * c
return d
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)

if (det > 0):


print("The quadratic equation has two real roots.")
elif (det == 0):
print("The quadratic equation has one real root.")
else:
print("The quadratic equation doesn't have any real root.“)
B3. Write a python 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):
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("Entered values are :")
print("Number 1:",n1," Number 2: ",n2)

print("Returned value from swap function:")


#calling the function to get the returned value
n1, n2 = swapN(n1, n2)
print("Number 1:",n1," Number 2: ",n2)
CHAPTER 8 : STRINGS
B4) Write a python 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)
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)
totalSpace = 0
for b in userInput:
if b.isspace():
totalSpace += 1

print("Total Words in the Input :",(totalSpace + 1))


B5) 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")
B6) Write a python program 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)
Chapter 9 : Lists

B7) Write a python 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)
B8) Write a python function that returns the largest element of the list
passed as parameter.

#Without using max() function of the list


def largestNum(list1):
length = len(list1)
num = 0
for i in range(length):
if(i == 0 or list1[i] > num):
num = list1[i]
return num

list1 = [1, 2, 3, 4, 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)
B9) Write a python 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.
#function to remove the duplicate elements
def removeDup(list1):
length = len(list1)
#Defining a new list for adding unique elements
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
#Defining empty list
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)
#Printing the list
print("The list entered is:",list1)

#Printing the list without any duplicate elements


print("The list without any duplicate element is:",removeDup(list1))
Chapter 10 : Tuples and Dictionaries
B10) Write a python 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()]
#Program to read email id of n number of students. Store these numbers 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.
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)
B11) Write a python 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 emailid 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")
B12a) 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': 1, 'n': 1, 'd': 1, ' ': 2, 'P': 1, 'U': 1, 'C': 1, 'o': 1, 'u': 1, 'r': 1, 's': 1, 'e': 1}

myStr="2nd PU Course"
print("The input string is:",myStr)
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)
B12b) 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]))

You might also like