0% found this document useful (0 votes)
2 views42 pages

Python Lab Manual

The document contains various Python programming exercises, including creating lists, calculating areas of shapes, manipulating tuples, and handling file operations. It also covers object-oriented programming concepts like classes and inheritance through examples such as an Employee class and a BankAccount class. Additionally, it introduces GUI programming using Tkinter for calculating compound interest.

Uploaded by

reach2bs
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)
2 views42 pages

Python Lab Manual

The document contains various Python programming exercises, including creating lists, calculating areas of shapes, manipulating tuples, and handling file operations. It also covers object-oriented programming concepts like classes and inheritance through examples such as an Employee class and a BankAccount class. Additionally, it introduces GUI programming using Tkinter for calculating compound interest.

Uploaded by

reach2bs
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

Python Programming Lab

PART A

1. Write a program create list with N elements. find all unique elements in the list.
If an element is found only once in the list, then add that element to the unique list.

Program

# Read number of elements

N = int(input("Enter number of elements: "))

# Create the list

lst = []

for i in range(N):

elem = input(f"Enter element {i+1}: ")

[Link](elem)

# Find unique elements

unique_list = []

for item in lst:

if [Link](item) == 1:

unique_list.append(item)

# Display results

print("Original List:", lst)

print("Unique Elements List:", unique_list)

Output

Enter number of elements: 6

Enter element 1: 10

Enter element 2: 20

Enter element 3: 10

1
Python Programming Lab

Enter element 4: 30

Enter element 5: 40

Enter element 6: 20

Original List: ['10', '20', '10', '30', '40', '20']

Unique Elements List: ['30', '40']

2. Program, using user-defined functions to find the area of rectangle, square,


circle and triangle by accepting suitable input parameters from user.

Formulas Used

 Area of Rectangle = length × breadth

 Area of Square = side × side

 Area of Circle = π × radius²

 Area of Triangle = ½ × base × height

Algorithm

1. Define separate functions for each shape.

2. Accept required inputs from the user.

3. Calculate the area using the respective formula.

4. Display the result.

Program:

import math

# Function to find area of rectangle

def area_rectangle(length, breadth):

return length * breadth

2
Python Programming Lab

# Function to find area of

square def area_square(side):

return side * side

# Function to find area of

circle def area_circle(radius):

return [Link] * radius *

radius # Function to find area of

triangle def area_triangle(base,

height):

return 0.5 * base * height

# Accept input from user

l = float(input("Enter length of rectangle: "))

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

print("Area of Rectangle:", area_rectangle(l, b))

s = float(input("\nEnter side of square: "))

print("Area of Square:", area_square(s))

r = float(input("\nEnter radius of circle: "))

print("Area of Circle:", area_circle(r))

base = float(input("\nEnter base of triangle: "))

height = float(input("Enter height of triangle: "))

print("Area of Triangle:", area_triangle(base,

height)) Output:

Enter length of rectangle: 5

Enter breadth of rectangle: 4

Area of Rectangle: 20
3
Python Programming Lab

Enter side of square: 6

Area of Square: 36

Enter radius of circle: 7

Area of Circle: 153.94

Enter base of triangle: 10

Enter height of triangle: 5

Area of Triangle: 25

3. Consider a tuple t1= (1,2,5,7,9,2,4,6,8,10). Write a program to perform following


operations

a. Print half the values of tuple in one line and the other half in the next line.
b. Print another tuple whose values are even numbers in the given tuple.
c. Concatenate a tuple t2 (11,13,15) with t1.
d. Return maximum and minimum value from this tuple.

Program:-
# Given tuple

t1 = (1, 2, 5, 7, 9, 2, 4, 6, 8, 10)

# a) Print first half and second half of the tuple

mid = len(t1) // 2

print("First half of tuple:")

print(t1[:mid])

4
Python Programming Lab

print("Second half of tuple:")

print(t1[mid:])

# b) Create another tuple with even numbers

even_tuple = ()

for item in t1:

if item % 2 == 0:

even_tuple = even_tuple + (item,)

print("Tuple with even numbers:", even_tuple)

# c) Concatenate tuple t2 with t1

t2 = (11, 13, 15)

concatenated_tuple = t1 + t2

print("Concatenated tuple:",

concatenated_tuple) # d) Find maximum and

minimum values print("Maximum value:",

max(t1)) print("Minimum value:", min(t1))

Output:-

First half of tuple:

(1, 2, 5, 7, 9)

Second half of tuple:

(2, 4, 6, 8, 10)

Tuple with even numbers: (2, 2, 4, 6, 8, 10)

Concatenated tuple: (1, 2, 5, 7, 9, 2, 4, 6, 8, 10, 11, 13, 15)

Maximum value: 10

Minimum value: 1

5
Python Programming Lab

4. Write a function that takes a sentence as input from the user and calculates the
frequency of each letter. Use a variable of dictionary type to maintain the count.

Explanation

This program defines a function that accepts a sentence from the user and calculates the
frequency of each letter.
A dictionary is used to store each letter as a key and its count as the value.

Program:
def letter_frequency(sentence):
freq = {}
for ch in sentence:
if [Link](): # consider only letters
ch = [Link]() # convert to
lowercase if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
return freq
# Accept input from user
sentence = input("Enter a sentence: ")
# Call function
result = letter_frequency(sentence)
# Display result
print("Letter Frequency:")
for letter, count in [Link]():
print(letter, ":", count)
Output:
Enter a sentence: Hello World
Letter Frequency:
h:1
e:1
l:3

6
Python Programming Lab

o:2
w:1
r:1
d:1
5. Write a program to create a text file and compute the number of characters, words
and lines in a file. Program using user defined exception class that will ask the user to
enter a number until he guesses a stored number correctly. To help them figure it out, a
hint is provided whether their guess is greater than or less than the stored number using
user defined exceptions.

Program:

# Create and write to a file

with open("[Link]", "w") as file:

[Link]("Python is easy to learn.\n")

[Link]("File handling is important.\n")

[Link]("This is a sample file.")

# Initialize counters

lines = 0

words = 0

characters = 0

# Read file and count

with open("[Link]", "r") as file:

for line in file:

lines += 1

characters += len(line)

words += len([Link]())

7
Python Programming Lab

# Display results

print("Number of lines:", lines)

print("Number of words:", words)

print("Number of characters:", characters)

Output:

Number of lines: 3

Number of words: 12

Number of characters: 79

6. Write Python programs to demonstrate the following:


i) input()
ii) print()
iii) sep attribute
iv) end attribute
v) Replacement operator ({})

Program:

# input() function

name = input("Enter your name: ")

age = input("Enter your age: ")

# print() function

print("User Details")

# sep attribute

print("Name", name, "Age", age, sep=" | ")

# end attribute

print("Thank you", end=" ")

print("for using Python")

8
Python Programming Lab

# Replacement operator {}

print("Name: {}, Age: {}".format(name, age))

Output:

Enter your name: hello world

Enter your age: 18

User Details

Name | hello world | Age | 18

Thank you for using Python

Name: hello world, Age: 18

[Link] the following control transfer statements in Python with suitable


examples. i)break ii) continue iii) pass

i) break

Statement

Explanation

The break statement is used to terminate the loop immediately when a specific condition is
satisfied.

Program:

for i in range(1, 6):

if i == 4:

break

print(i)

Output:

9
Python Programming
Lab

ii) continue

Statement

Explanation

The continue statement is used to skip the current iteration of the loop and continue with the
next iteration.

Program

for i in range(1, 6):

if i == 3:

continue

print(i)

Output:

iii) pass

Statement

Explanation

The pass statement is a null statement. It is used when a statement is syntactically required
but no action is needed.

Program

for i in range(1, 6):

if i == 3:

pass

print(i)

BIHE DVG 11
Python Programming
Lab
output

12345

BIHE DVG 12
Python Programming
Lab

PART B

1. Program to create a class Employee with empno, name, depname,


designation, age and salary and perform the following function.

i) Accept details of N employees

ii) Search given employee using empno

iii)Display employee details in neat

format. Explanation

In this program, a class Employee is created with data members such as empno, name,
depname, designation, age, and salary.
The program performs the following operations:

1. Accept details of N employees

2. Search an employee using empno

3. Display employee details in a neat format

Program:

class Employee:

def init (self, empno, name, depname, designation, age, salary):

[Link] = empno

[Link] = name

[Link] = depname

[Link] = designation

[Link] = age

[Link] = salary

def display(self):

print(" ")

BIHE DVG 13
Python Programming
Lab

print("Employee No :", [Link])

print("Name :", [Link])

print("Department :", [Link])

print("Designation :", [Link])

print("Age :", [Link])

print("Salary :", [Link])

print(" ")

# Accept details of N employees

employees = []

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

for i in range(n):

print("\nEnter details of employee", i + 1)

empno = int(input("Employee No: "))

name = input("Name: ")

depname = input("Department Name:

") designation = input("Designation: ")

age = int(input("Age: "))

salary = float(input("Salary: "))

emp = Employee(empno, name, depname, designation, age, salary)

[Link](emp)

# Search employee using empno

search_empno = int(input("\nEnter employee number to search: "))

found = False

for emp in employees:

BIHE DVG 14
Python Programming
Lab

if [Link] == search_empno: print("\

nEmployee Found:") [Link]()

found = True

break

if not found:

print("Employee not found")

Output:

Enter number of employees: 2

Enter details of employee 1

Employee No: 101

Name: Ravi

Department Name: IT

Designation: Programmer

Age: 25

Salary: 35000

Enter details of employee 2

Employee No: 102

Name: Anita

Department Name: HR

Designation: Manager

Age: 30

Salary: 45000

BIHE DVG 15
Python Programming
Lab

Enter employee number to search: 102

Employee Found:

Employee No : 102

Name : Anita

Department : HR

Designation : Manager

Age 30

Salary 45000

2. Write a program menu driven to create a BankAccount class. class should


support the following methods for i) Deposit ii) Withdraw iii) GetBalanace.
Create a subclass Savings Account class that behaves just like a BankAccount, but
also has an interest rate and a method that increases the balance by the
appropriate amount of interest.

Explanation

In this program, a BankAccount class is created with methods deposit, withdraw, and
getBalance.
A SavingsAccount class is derived from the BankAccount class using inheritance.
The SavingsAccount class includes an additional data member interest rate and a method to
add interest to the balance.
The program is menu driven, allowing the user to perform operations repeatedly.

Program:-

class BankAccount:

def init (self, balance=0):

BIHE DVG 16
Python Programming
Lab

[Link] = balance

def deposit(self, amount):

[Link] += amount

print("Amount deposited:", amount)

def withdraw(self, amount):

if amount <= [Link]:

[Link] -= amount

print("Amount withdrawn:", amount)

else:

print("Insufficient balance")

def getBalance(self):

print("Current Balance:", [Link])

class SavingsAccount(BankAccount):

def init (self, balance=0, interest_rate=0):

super(). init (balance)

self.interest_rate = interest_rate

def addInterest(self):

interest = [Link] * self.interest_rate / 100

[Link] += interest

print("Interest added:", interest)

# Create SavingsAccount object

balance = float(input("Enter initial balance: "))

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

BIHE DVG 17
Python Programming
Lab

account = SavingsAccount(balance, rate)

while True:

print("\n----- MENU-----")

print("1. Deposit")

print("2. Withdraw")

print("3. Get Balance")

print("4. Add Interest")

print("5. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:

amt = float(input("Enter amount to deposit: "))

[Link](amt)

elif choice == 2:

amt = float(input("Enter amount to withdraw: "))

[Link](amt)

elif choice == 3:

[Link]()

elif choice == 4:

[Link]()

elif choice == 5:

print("Thank you! Exiting program.")

break

else:

print("Invalid choice")

BIHE DVG 18
Python Programming
Lab

Output:

Enter initial balance: 1000

Enter interest rate: 5

----- MENU -----

1. Deposit

2. Withdraw

3. Get Balance

4. Add Interest

5. Exit

Enter your choice: 1

Enter amount to deposit: 500

Amount deposited: 500

Enter your choice: 4

Interest added: 75.0

Enter your choice: 3

Current Balance: 1575.0

3. Create a GUI to input Principal amount, rate of interest and number of years,
Calculate Compound interest. When button submit is pressed Compound interest
should be displayed in a textbox. When clear button is pressed all contents should be
cleared.

BIHE DVG 19
Python Programming
Lab

Explanation

This program creates a Graphical User Interface (GUI) using the Tkinter library.
The user enters:

 Principal Amount

 Rate of Interest

 Number of Years

When the Submit button is pressed, the Compound Interest is calculated and displayed in a
textbox.
When the Clear button is pressed, all input and output fields are cleared.

Formula Used

Compound Interest 𝑅 𝑇

= 𝑃 × (1+ −𝑃
)
Program: 100

import tkinter as tk

# Function to calculate compound interest

def calculate_ci():

p = float(entry_principal.get())

r = float(entry_rate.get())

t = float(entry_years.get())

ci = p * ((1 + r / 100) ** t) - p

entry_result.delete(0, [Link])

entry_result.insert(0, str(round(ci, 2)))

# Function to clear all fields

BIHE DVG 11
0
Python Programming Lab

def clear_fields():

entry_principal.delete(0, [Link])

entry_rate.delete(0, [Link])

entry_years.delete(0, [Link])

entry_result.delete(0, [Link])

# Create main window

window = [Link]()

[Link]("Compound Interest

Calculator") [Link]("350x300")

# Labels

[Link](window, text="Principal Amount").pack()

entry_principal = [Link](window)

entry_principal.pack()

[Link](window, text="Rate of Interest").pack()

entry_rate = [Link](window)

entry_rate.pack()

[Link](window, text="Number of Years").pack()

entry_years = [Link](window)

entry_years.pack()

[Link](window, text="Compound Interest").pack()

entry_result = [Link](window)

entry_result.pack()

# Buttons

[Link](window, text="Submit", command=calculate_ci).pack(pady=5)

BIHE DVG 20
Python Programming Lab

[Link](window, text="Clear",

command=clear_fields).pack(pady=5) # Run GUI

[Link]()

Output:

4 Write a GUI program to implement Simple Calculator

Explanation

This program creates a Simple Calculator GUI using the Tkinter library.
It allows the user to perform Addition, Subtraction, Multiplication, and Division
operations on two numbers.
The result is displayed in a textbox.

Program

import tkinter as tk

# Function to perform calculation

def calculate():

n1 = float(entry_num1.get())

n2 = float(entry_num2.get())

op = [Link]()

if op == "Add":

result = n1 + n2

BIHE DVG 21
Python Programming Lab

elif op == "Subtract":

result = n1 - n2

elif op == "Multiply":

result = n1 * n2

elif op == "Divide":

if n2 != 0:

result = n1 / n2

else:

result = "Error"

else:

result = ""

entry_result.delete(0, [Link])

entry_result.insert(0, str(result))

# Function to clear all fields

def clear():

entry_num1.delete(0, [Link])

entry_num2.delete(0, [Link])

entry_result.delete(0, [Link])

# Create main window

window = [Link]()

[Link]("Simple Calculator")

[Link]("300x300")

# Labels and Entry boxes

[Link](window, text="Number

1").pack()
BIHE DVG 22
Python Programming Lab

entry_num1 = [Link](window)

entry_num1.pack()

[Link](window, text="Number 2").pack()

entry_num2 = [Link](window)

entry_num2.pack()

[Link](window, text="Operation").pack()

operator = [Link]()

[Link]("Add")

[Link](window, operator, "Add", "Subtract", "Multiply", "Divide").pack()

[Link](window, text="Result").pack()

entry_result = [Link](window)

entry_result.pack()

# Buttons

[Link](window, text="Calculate",

command=calculate).pack(pady=5) [Link](window, text="Clear",

command=clear).pack(pady=5)

# Run the GUI

[Link]()

Output:

BIHE DVG 23
Python Programming Lab

5 Create a table student table (regno, name and marks in 3 subjects) using
Sqlite3/MYSQL and perform the followings

a. To accept the details of students and store it in database.

b. To display the details of all the students

c. Delete particular student record using regno.

Explanation

BIHE DVG 24
Python Programming Lab

This program uses SQLite3 database to create a student table with fields regno, name, and
marks in three subjects.
It performs the following operations:

i. Accept student details and store them in the database

ii. Display details of all students

iii. Delete a particular student record using regno

Program:

import sqlite3

# Connect to database

conn = [Link]("[Link]")

cur = [Link]()

# Create table

[Link]("""

CREATE TABLE IF NOT EXISTS student

( regno INTEGER PRIMARY KEY,

name TEXT,

marks1 INTEGER,

marks2 INTEGER,

marks3 INTEGER

""")

BIHE DVG 25
Python Programming Lab

# Function to insert student details

def insert_student():

regno = int(input("Enter Reg No: "))

name = input("Enter Name: ")

m1 = int(input("Enter Marks 1: "))

m2 = int(input("Enter Marks 2: "))

m3 = int(input("Enter Marks 3: "))

[Link]("INSERT INTO student VALUES (?, ?, ?, ?, ?)",

(regno, name, m1, m2, m3))

[Link]()

print("Student record inserted successfully")

# Function to display all students

def display_students():

[Link]("SELECT * FROM student")

rows = [Link]()

print("\nRegNo Name Marks1 Marks2 Marks3")

print(" ")

for row in rows:

print(row[0], row[1], row[2], row[3], row[4])

# Function to delete student by regno

def delete_student():

regno = int(input("Enter Reg No to delete: "))

[Link]("DELETE FROM student WHERE regno = ?",

(regno,)) [Link]()

BIHE DVG 26
Python Programming Lab

print("Student record deleted")

# Menu-driven program

while True:

print("\n--- MENU ---")

print("1. Insert Student")

print("2. Display Students")

print("3. Delete Student")

print("4. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:

insert_student()

elif choice == 2:

display_students()

elif choice == 3:

delete_student()

elif choice == 4:

break

else:

print("Invalid choice")

[Link]()

Output:-

--- MENU ---

1. Insert Student

BIHE DVG 27
Python Programming Lab

2. Display Students

3. Delete Student

4. Exit

Enter your choice: 1

Enter Reg No:

106 Enter Name:

Tommy Enter

Marks 1: 50

Enter Marks 2: 50

Enter Marks 3: 40

Student record inserted successfully

--- MENU ---

1. Insert Student

2. Display Students

3. Delete Student

4. Exit

Enter your choice: 1

Enter Reg No:

110 Enter Name:

Net Enter Marks

1: 50

Enter Marks 2: 40

Enter Marks 3: 40

Student record inserted successfully


BIHE DVG 28
Python Programming Lab

--- MENU ---

1. Insert Student

2. Display Students

3. Delete Student

4. Exit

Enter your choice: 2

RegNo Name Marks1 Marks2 Marks3

101 john 30 40 50

105 tom 50 4 45

106 Tommy 50 50 40

110 Net 50 40 40

--- MENU ---

1. Insert Student

2. Display Students

3. Delete Student

4. Exit

Enter your choice: 3

Enter Reg No to delete: 105

Student record deleted

BIHE DVG 29
Python Programming Lab

--- MENU ---

1. Insert Student

2. Display Students

3. Delete Student

4. Exit

Enter your choice: 2

RegNo Name Marks1 Marks2 Marks3

101 john 30 40 50

106 Tommy 50 50 40

110 Net 50 40 40

--- MENU ---

1. Insert Student

2. Display Students

3. Delete Student

4. Exit

Enter your choice: 4

6. Create a table employee (empno, name and salary) using Sqlite3/MySQL and
perform the followings

a. To accept the details of employees and store it in database.

b. To display the details of a specific employee

BIHE DVG 30
Python Programming Lab

c. To display employee details whose salary lies within a certain range.

Explanation

This program uses SQLite3 to create an employee table with fields:

 empno (Employee Number)

 name (Employee Name)

 salary (Employee

Salary) The program

performs:

i. Insert employee details into the database

ii. Display details of a specific employee

iii. Display details of employees within a salary range

Program:

import sqlite3

# Connect to database

conn = [Link]("[Link]")

cur = [Link]()

# Create employee table if not exists

[Link]("""

CREATE TABLE IF NOT EXISTS employee (

empno INTEGER PRIMARY KEY,

name TEXT, salary

REAL

"

"
31
Python Programming Lab
"

[Link]()

32
Python Programming Lab

# Function to insert employee details

def insert_employee():

empno = int(input("Enter Employee Number: "))

name = input("Enter Name: ")

salary = float(input("Enter Salary: "))

[Link]("INSERT INTO employee VALUES (?, ?, ?)", (empno, name, salary))

[Link]()

print("Employee record inserted successfully")

# Function to display specific employee details

def display_employee():

empno = int(input("Enter Employee Number to display: "))

[Link]("SELECT * FROM employee WHERE empno=?", (empno,))

row = [Link]()

if row:

print("\nEmpNo Name Salary")

print(" ")

print(row[0], row[1], row[2])

else:

print("Employee not found")

# Function to display employees within a salary range

def display_salary_range():

low = float(input("Enter minimum salary: "))

high = float(input("Enter maximum salary: "))

33
Python Programming Lab

[Link]("SELECT * FROM employee WHERE salary BETWEEN ? AND ?", (low,


high))

rows = [Link]()

if rows:

print("\nEmpNo Name Salary")

print(" ")

for row in rows:

print(row[0], row[1], row[2])

else:

print("No employees found in this salary range")

# Menu-driven program

while True:

print("\n--- MENU ---")

print("1. Insert Employee")

print("2. Display Specific Employee")

print("3. Display Employees by Salary Range")

print("4. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:

insert_employee()

elif choice == 2:

display_employee()

elif choice == 3:

display_salary_range()

34
Python Programming Lab

elif choice == 4:

break

else:

print("Invalid choice")

[Link]()

Output:

--- MENU ---

1. Insert Employee

2. Display Specific Employee

3. Display Employees by Salary Range

4. Exit

Enter your choice: 1

Enter Employee Number: 101

Enter Name: Ravi

Enter Salary: 35000

Employee record inserted successfully

--- MENU ---

1. Insert Employee

2. Display Specific Employee

3. Display Employees by Salary Range

4. Exit

Enter your choice: 2

Enter Employee Number to display: 101

35
Python Programming Lab

EmpNo Name Salary

101 Ravi 35000.0

--- MENU ---

1. Insert Employee

2. Display Specific Employee

3. Display Employees by Salary Range

4. Exit

Enter your choice: 3

Enter minimum salary: 30000

Enter maximum salary: 40000

EmpNo Name Salary

101 Ravi 35000.0

--- MENU ---

1. Insert Employee

2. Display Specific Employee

3. Display Employees by Salary Range

4. Exit

Enter your choice: 4

36
Python Programming Lab

7. WAP in Python for Linear Search and Binary Search.

Explanation

 Linear Search: Sequentially checks each element until the target is found.

 Binary Search: Efficient search for sorted lists, repeatedly dividing the
search interval in half.

Program:

# Linear Search Function

def linear_search(arr,

target):

for i in range(len(arr)):

if arr[i] == target:

return i # Return index if found

return -1 # Not found

# Binary Search Function

def binary_search(arr, target):

[Link]() # Binary search requires sorted list

low = 0

high = len(arr) - 1

while low <= high:

mid = (low + high) // 2

if arr[mid] == target:

return mid

elif arr[mid] < target:

low = mid + 1

37
Python Programming Lab

else:

high = mid - 1

return -1

# Accept input from user

arr = list(map(int, input("Enter elements of the list separated by space: ").split()))

target = int(input("Enter element to search: "))

# Linear Search

result_linear = linear_search(arr, target)

if result_linear != -1:

print(f"Linear Search: Element found at index {result_linear}")

else:

print("Linear Search: Element not found")

# Binary Search

result_binary = binary_search(arr, target)

if result_binary != -1:

print(f"Binary Search: Element found at index {result_binary}")

else:

print("Binary Search: Element not found")

Output:

Enter elements of the list separated by space: 10 20 30 40 50 60 70

Enter element to search: 30

Linear Search: Element found at index 2

Binary Search: Element found at index 2

38
Python Programming Lab
[Link] in Python for Selection Sort and Bubble Sort.

Explanation

 Selection Sort: Repeatedly selects the smallest (or largest) element from the
unsorted part and moves it to the sorted part.

 Bubble Sort: Repeatedly compares adjacent elements and swaps them if they are
in the wrong order

Program:

# Selection Sort Function

def selection_sort(arr):

n = len(arr)

for i in range(n-1):

min_idx = i

for j in range(i+1, n):

if arr[j] < arr[min_idx]:

min_idx = j

arr[i], arr[min_idx] = arr[min_idx], arr[i]

return arr

# Bubble Sort Function

def bubble_sort(arr):

n = len(arr)

for i in range(n-1):

for j in range(n-1-i):

if arr[j] > arr[j+1]:

arr[j], arr[j+1] = arr[j+1], arr[j]

return arr

39
Python Programming Lab

# Accept input from user

arr = list(map(int, input("Enter elements of the list separated by space: ").split()))

# Selection Sort

sorted_selection = selection_sort([Link]())

print("Sorted List using Selection Sort:", sorted_selection)

# Bubble Sort

sorted_bubble = bubble_sort([Link]())

print("Sorted List using Bubble Sort:", sorted_bubble)

Output:

Enter elements of the list separated by space: 64 34 25 12 22 11 90

Sorted List using Selection Sort: [11, 12, 22, 25, 34, 64, 90]

Sorted List using Bubble Sort: [11, 12, 22, 25, 34, 64, 90]

31
0

You might also like