0% found this document useful (0 votes)
10 views

Python Practice Programs (Extended Version)

Uploaded by

Abhishek Kadakol
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Python Practice Programs (Extended Version)

Uploaded by

Abhishek Kadakol
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Competence, Commitment and Teamwork

SDME Society’s

SDM COLLEGE OF ENGINEERING AND TECHNOLOGY, DHARWAD – 580 002


(An Autonomous Institution affiliated to Visvesvaraya Technological University, Belagavi - 590 018)

Department of Electronics and Communication Engineering

Practice Programs for Python


In connection with the course:
Introduction to Python Programming Laboratory
Course Code: 22PLC25B
(Integrated Course)
Semester: II

Dr. S. S. Navalgund Dr. Shreedhar A. Joshi


Course Instructor HOD, ECE

Academic Year 2023 – 24


Table of Contents
Sl. No. Programming Exercise Page No.
1 Wishing the user 3
2 Finding the area of a rectangle given the length and breadth 4
3 Finding the area of a triangle given its base and 5
height
4 Finding the area of a triangle using the Heron’s formula 6
5 Finding the area of a circle given the radius 8
6 Swapping two numbers 9
7 Reversing a given string and checking for palindrome 11
8 Checking if a given number is positive or negative, and print the 13
appropriate message.
9 Finding the smallest and largest numbers from a set of numbers 14
10 Finding the even and odd numbers, and their respective count 16
from a given dataset of numbers.
11 Checking for a prime number 18
12 Renaming multiple files in a folder by adding a prefix or suffix to 20
their names
13 Implementing simple calculator using the functions 22
1. Write a program to wish a user.
Algorithm
1: Begin
2: Read the name of the user
3: Print the message with greetings
4: End

#Program to wish a user


print(“Program to wish a user”)
NameUser = input(“Enter your name: ”)
Print(“Hello, greeting to you “, NameUser)

Sample output 1
Program to wish a user
Enter your name: Jay
Hello, greetings to you Jay

Sample output 2
Program to wish a user
Enter your name: Richard
Hello, greetings to you Richard
2. Write a program for finding the area of a rectangle given the length and breadth.

Algorithm
1: Begin
2: Read the value of length of rectangle from the user.
3: Read the value of breadth of rectangle from the user.
4: Compute the area of rectangle by multiplying both values.
5: Print the output area.
4: End

#Program to find the area of a rectangle given the length and breadth
print(“Program to find the area of a rectangle given the length and breadth”)
LengthRect = int(input(“Enter the value of length : ”))
BreadthRect = int(input(“Enter the value of breadth : ”))
AreaRect = LengthRect * BreadthRect
print(“The area of rectangle is : “, AreaRect, “square units”)

Sample output 1
Program to find the area of a rectangle given the length and breadth
Enter the value of length : 10
Enter the value of breadth : 20
The area of rectangle is : 200 square units

Sample output 2
Program to find the area of a rectangle given the length and breadth
Enter the value of length : 25
Enter the value of breadth : 2
The area of rectangle is : 50 square units
3. Write a program for finding the area of a triangle given its base and height.
Algorithm
1: Begin
2: Read the value of base from the user.
3: Read the value of height from the user.
4: Compute the area of triangle by using the formula 0.5 * base * height.

5: Print the output area.


4: End

#Program to find the area of a triangle given the base and height
print(“Program to find the area of a triangle given the base and height”)
BaseTriangle = int(input(“Enter the value of base : ”))
HeightTriangle = int(input(“Enter the value of height : ”))
AreaTriangle = 0.5 * BaseTriangle * HeightTriangle
print(“The area of triangle is : “, AreaTriangle, “square units”)

Sample output 1
Program to find the area of a triangle given the base and height
Enter the value of base : 10
Enter the value of height : 20
The area of triangle is : 100 square units

Sample output 2
Program to find the area of a triangle given the base and height
Enter the value of base : 15
Enter the value of height : 37
The area of triangle is : 277.5 square units
4. Write a program to find the area of a triangle using the Heron’s formula.
Algorithm
1: Begin
2: Read the values of sides a, b and c from the user.
3: Compute the value of semi-perimeter s as (a +b +c)/2.
4: Compute the area of triangle by using the math library as math.sqrt(s*(s-a)*(s-b)*(s-c)).

5: Print the output area.


4: End

#Program to find the area of a triangle using the Heron’s formula


import math #import the math module for sqrt function
print(“Program to find the area of a triangle using the Heron’s formula”)
SideA = float(input(“Enter the value of SideA : ”))
SideB = float(input(“Enter the value of SideB : ”))
SideC = float(input(“Enter the value of SideC : ”))
s = (SideA + SideB + SideC) / 2.0
AreaTriangle = math.sqrt(s*(s-SideA)*(s-SideB)*(s-SideC))
print(“The area of triangle is : “, AreaTriangle, “square units”)

Sample output 1
Program to find the area of a triangle using the Heron’s formula
Enter the value of SideA : 5
Enter the value of SideB : 6
Enter the value of SideC : 7
The area of triangle is : 14.696938456699069 square units
Sample output 2
Program to find the area of a triangle using the Heron’s formula
Enter the value of SideA : 10
Enter the value of SideB : 10
Enter the value of SideC : 10
The area of triangle is : 43.30127018922193 square units

Sample output 3
Program to find the area of a triangle using the Heron’s formula
Enter the value of SideA : 0
Enter the value of SideB : 4
Enter the value of SideC : 5
Traceback (most recent call last):
File "C:/Users/HP/AppData/Local/Programs/Python/Python312-
32/areaTriangleHeronFormula.py", line 8, in <module>
AreaTriangle = math.sqrt(s*(s-SideA)*(s-SideB)*(s-SideC))
ValueError: math domain error

NOTE: We get a math error since any triangle cannot have zero as the length of it’s side.
5. Write a program to find the area of a circle given the radius.
Algorithm
1: Begin
2: Read the values of radius of the circle from the user.
3: Compute the value of area as 3.142 * r * r.
4: Print the computed area.

5: End

#Program to find the area of a circle given its radius


Import math
print(“Program to find the area of a circle given its radius”)
Radius = int(input(“Enter the value of radius of circle : ”))
CircleArea = math.pi * Radius * Radius
print(“The area of circle is : “, CircleArea, “square units”)

Sample output 1
Program to find the area of a circle given its radius
Enter the value of radius of circle : 1
The area of circle is : 3.142 square units

Sample output 2
Program to find the area of a circle given its radius
Enter the value of radius of circle : 0
The area of circle is : 0.0 square units

Sample output 3
Program to find the area of a circle given its radius
Enter the value of radius of circle : 6
The area of circle is : 113.112 square units
6. Write a program for Swapping two numbers.
Algorithm
1: Begin
2: Read the first number from the user.
3: Assign the value 5 to variable y.
4: Create a temporary variable swap and assign the value of x to it.
5: Assign the value of y to variable x.
6: Assign the value of temp to variable y.
7: Print the value of x with the message "After swapping value x:".
8: Print the value of y with the message "After swapping value y:".
9: End

Program Version 1
#Program to swap two numbers
print(“Program to swap two numbers”)
x=int(input(“Enter the first number :”))
y= int(input(“Enter the second number :”))
swap=x
print('After swapping value x:', y)
print('After swapping value y:', swap)

Sample output 1

Program to swap two numbers


Enter the first number : 21
Enter the second number : 45
After swapping value x: 45
After swapping value y: 21

Sample output 2
Program to swap two numbers
Enter the first number : 321
Enter the second number : 145
After swapping value x: 145
After swapping value y: 321
Program Version 2
#Program to swap two numbers using a third variable
print(“Program to swap two numbers”)
x = int(input(“Enter the first number :”))
y = int(input(“Enter the second number :”))
print(“Before swapping, x and y are : “, x, y)
Temp = x
x=y
y = Temp
print(“After swapping, x and y are : “, x, y)

Sample Output 1

Program to swap two numbers


Enter the first number :11
Enter the second number :44
Before swapping, x and y are : 11 44
After swapping, x and y are : 44 11
7. Write a program for reversing a given string and checking for palindrome.
1: Begin

2: Get the input string from the user.

3: Use string slicing to reverse the string and assign it to the variable ReversedString.

4: Print the reversed string.

5: Check if the input string is equal to the ReversedString.

6: If both are equal, print "The given string is a palindrome".

7: Otherwise, print "The given string is not a palindrome".

8: end

Program

#Program to find if a given string is palindrome

Print(“Program to find if a given string is palindrome“)

# Get the input string from the user

InString = input("Enter a string: ")

# Reverse the string using string slicing

ReversedString = input_string[::-1]

# Now, print the reversed string

print("Reversed string:", ReversedString)

if InString == ReversedString: #Check for both strings to be equal

print('The given string is palindrome')

else:

print('The given string is not palindrome')


Sample Output 1
Program to find if a given string is palindrome
Enter a string: simple
Reversed string: elpmis
The given string is not palindrome

Sample Output 2
Program to find if a given string is palindrome
Enter a string: Python
Reversed string: nohtyP
The given string is not palindrome

Sample Output 3
Program to find if a given string is palindrome
Enter a string: madam
Reversed string: madam
The given string is palindrome
8. Write a program to check if a given number is positive or negative, and print the
appropriate message.
1: Begin
2: Get the input number from the user.
3: Check if the input number is greater than 0.
4: If yes, then the number is positive. Display the message.
5: If no, then the number is negative. Display the message.
6: End
Program
#Program to find if a given number is positive or negative
print(“Program to find if a given number is positive or negative “)
# Get the input number from the user
InNum = input("Enter a number: ")
if InNum > 0: #Check if number is greater than 0
print(“The given number is positive”)
else:
print(“The given string is number is negative”)

NOTE: Avoid the input as zero, since it is defined as neither positive nor negative.
Sample Output 1
Program to find if a given number is positive or negative
Enter a number: 34
The given number is positive
Sample Output 2
Program to find if a given number is positive or negative
Enter a number: -2
The given number is negative
9. Write a program to find the smallest and largest numbers from a set of numbers.
1: Begin
2: Inside the function, perform the following.
2.1: Initialise the first element as the Largest and Smallest.
2.2: Using a for loop, perform the following operations.
2.2.1: Perform comparison of successive numbers with Largest and Smallest.
2.2.2: If the successive number is greater than the Largest, then assign the
number to Largest.
2.2.3: If the successive number is smaller than the Smallest, then assign the
number to Smallest.
2.3: Return the Largest and Smallest numbers to the calling function.
3: Print the results.
4: End
Program
#Program to find if a given number is even or odd
NOTE: Let us write a function FindLargestSmallest() which has the following details.
Argument is a list of numbers.
Return values are a tuple containing the largest and smallest numbers in the list.
The function raises ValueError if the input list is empty.

def FindLargestSmallest(Numbers):
# Check if the list is empty
if not Numbers:
raise ValueError("The input list cannot be empty.")

# Initialize variables to store the largest and smallest numbers seen so far
Largest = Numbers[0]
Smallest = Numbers[0]

# Iterate through the list and update the largest and smallest values if necessary
for Number in Numbers:
if Number > Largest:
Largest = Number
elif Number < Smallest:
Smallest = Number
return Largest, Smallest
# Example usage
Numbers = [5, 10, 2, 18, 7]
Largest, Smallest = FindLargestSmallest(Numbers)

print("The largest number is:", Largest)


print("The smallest number is:", Smallest)

Sample Output 1
Finding the largest and smallest numbers from a list
The largest number is: 18
The smallest number is: 2

NOTE: The students may read the contents of a list from the user, and build it with
different values. And, the largest and smallest numbers may be found out from that
list.
10. Write a program to find the even and odd numbers, and their respective count from a
given dataset of numbers.
Algorithm
1: Begin
2: Read the size of dataset from the user.
3: Create an empty list called MyList.
4: Initialize the variables CountEven and CountOdd to count the occurrences of
respective numbers.
5: Use a for loop and iterate InCount number of times.
5.1: Read the next number in the dataset.
5.2: Check if the number is even or odd by checking the remainder after division by
2.
5.3: If the remainder is 0, then the number is even, hence increment the CountEven.
Else, the number is odd, thus increment the CountOdd variable.
6: Print the values of CountEven and CountOdd on the screen.

#Program to find even or odd numbers and their count from a set of numbers

print("Program to find even or odd numbers and their count from a set of numbers ")
# Get the size of input dataset from the user
InCount = int(input("Enter the size of dataset: "))
MyList = []
CountEven = 0
CountOdd = 0
for i in range(InCount):
InNum = int(input("Enter the value of number {}:".format(i+1)))
MyList.append(InNum)
if MyList[i] % 2 == 0: #Check if remainder is 0
CountEven = CountEven + 1
else:
CountOdd = CountOdd + 1
print("The count of even numbers is ", CountEven)
print("The ount of odd numbers is ", CountOdd)

Sample Output 1
Program to find even or odd numbers and their count from a set of numbers
Enter the size of dataset: 3
Enter the value of number 1:11
Enter the value of number 2:22
Enter the value of number 3:33
The count of even numbers is 1
The count of odd numbers is 2

Sample Output 2
Program to find even or odd numbers and their count from a set of numbers
Enter the size of dataset: 0
The count of even numbers is 0
The count of odd numbers is 0
NOTE: Since the dataset size is zero, no input numbers are read in this case.
Sample Output 3
Program to find even or odd numbers and their count from a set of numbers
Enter the size of dataset: 5
Enter the value of number 1:22
Enter the value of number 2:22
Enter the value of number 3:44
Enter the value of number 4:66
Enter the value of number 5:88
The count of even numbers is 5
The count of odd numbers is 0
11. Write a program to check if a given number is prime or not. Print the appropriate
message on the screen.
Algorithm
1: Begin
2: Read the input number from the user.
3: Check if the input number is less than 2.
4: If true, then assign the variable Prime as False. (Boolean value)
5: If not, then assign the variable Prime as True.
6: Use a loop to iterate from 2 to the square root of the number plus 1.
7: Check if the number is divisible by the current iteration value i.
8: If yes, assign Prime as False and break out of the loop.
9: Print the result based on the value of Prime.
10: If the variable Prime is True, then print the number to be a prime.
11: If the variable Pime is False, print the number as not prime.
12: End

Program
#Program to check if a given number is prime or not
print("Program to check if a given number is prime or not")

# Read the input number from the user


Number = int(input("Enter a number: "))

# Check if the number is prime


if Number < 2:
Prime = False
else:
Prime = True

for i in range(2, int(Number ** 0.5) + 1):


if Number % i == 0:
Prime = False
Break

# Print the result


if Prime:
print(Number, "is a prime number.")
else:
print(Number, "is not a prime number.")
Sample Output 1
Program to check if a given number is prime or not
Enter a number: 22
22 is not a prime number.

Sample Output 2
Program to check if a given number is prime or not
Enter a number: 91
91 is not a prime number.
12. Write a program to rename multiple files in a folder by adding a prefix as your USN
and suffix as the year 2024, to their existing names.
Algorithm
1: Begin
2: Import the os module into the program.
3: Set a variable FolderPath to indicate all the files in a desired folder.
4: Set the desired prefix (here, the USN) and suffix (here, the year 2024) variables.
5: Use the os.listdir() function to get the list of files in the folder and store it in the files
variable.
6: Loop over each file in the files list.
7: Inside the loop, perform the following actions.
7.1: Construct the new file name by concatenating the prefix, original file name,and
suffix.
7.2: Get the full paths of the original and new file names by joining the FolderPath
with the file names using os.path.join().
7.3: Use the os.rename() function to rename the file by passing the old path and new
path as arguments.
8: After the loop finishes, print a message indicating that the files have been renamed
successfully.

Program
# program to rename multiple files in a folder by adding a prefix as your USN and suffix
# as the year 2024, to their existing names

print(“File renaming with prefix and suffix”)

# Indicate the folder path where the desired files are located
FolderPath = "C:\\Python312\\MyPrograms\\MyFiles" #sample folder, use your
#own folder accordingly

# Read the Prefix or suffix to be added from the user


Prefix = input(“Enter the prefix”)
Suffix = input(“Enter the suffix")

# Get the list of files in the folder


Files = os.listdir(FolderPath)

# Loop over the files and rename them


for File in Files:
NewName = Prefix + File + Suffix # Construct the new file name
OldPath = os.path.join(FolderPath, File)# Get the full paths of the original and
# new file names
NewPath = os.path.join(FolderPath, NewName)
os.rename(OldPath, NewPath) # Rename the file

print("Files renamed successfully.")


Sample Output
Assume that the above folder contains two files, let us say, file1.rtf and file2.txt. Also
assume that the prefix supplied by the user is ‘Python’ and suffix is 2024, then the folder
will contain the files Pythonfile1.rtf2024 and Pythonfile2.txt2024.
13. Write a program to implement a simple calculator using the functions. The menu-
driven code needs to present the functionalities available.
Algorithm
1: Begin
2: Print the available functionalities of the calculator to the user.
3: Read the user's choice and assign it to the variable Choice.
4: Read the first number from the user and assign it to the variable Num1.
5: Read the second number from the user and assign it to the variable Num2.
6: If Choice is 1, call the Add() with arguments Num1 and Num2, and print the result.
7: If Choice is 2, call the Sub() with arguments Num1 and Num2, and print the result.
8: If Choice is 3, call the Mul() with arguments Num1 and Num2, and print the result.
9: If Choice is 4, call the Div() with arguments Num1 and Num2, and print the result.
10: If Choice is invalid, print "Wrong choice…sorry!!!"
11: End

Program
def Add(Num1, Num2): #Define the function for Addition
return Num1 + Num2

def Sub(Num1, Num2): #Define the function for Subtraction


return Num1 - Num2

def Mul(Num1, Num2): #Define the function for Multiplication


return Num1 * Num2

def Div(Num1, Num2): #Define the function for Division


return Num1 / Num2

print(“Program to implement a simple calculator using the functions”)


print(“Choice 1 : Addition”) #Menu for selecting the choice
print(”Choice 2 : Subtraction”)
print(”Choice 3 : Multiplication”)
print(”Choice 4 : Division”)
Choice=int(input(“Enter your choice:”))
Num1=float(input(“Enter the first number:”))
Num2=float(input(“Enter the second number:”))

if Choice==1:
print(“Sum = “, Add(Num1, Num2))
elif Choice==2:
print(“Difference = “, Sub(Num1, Num2))
elif Choice==3:
print(“Product = “, Mul(Num1, Num2))
elif Choice==4:
print(“Result = “, Div(Num1, Num2))
else:
print('Wrong choice…sorry!!!')

Sample Output 1
Program to implement a simple calculator using functions
Choice 1 : Addition
Choice 2 : Subtraction
Choice 3 : Multiplication
Choice 4 : Division
Enter your choice:1
Enter the first number:1.2
Enter the second number:2.3
Sum = 3.5

Sample Output 2
Program to implement a simple calculator using functions
Choice 1 : Addition
Choice 2 : Subtraction
Choice 3 : Multiplication
Choice 4 : Division
Enter your choice:3
Enter the first number:1.5
Enter the second number:2.5
Product = 3.75

Sample Output 3
Program to implement a simple calculator using functions
Choice 1 : Addition
Choice 2 : Subtraction
Choice 3 : Multiplication
Choice 4 : Division
Enter your choice:5
Enter the first number:1
Enter the second number:2
Wrong choice...sorry!!!

You might also like