0% found this document useful (0 votes)
5 views32 pages

Python Application Development Experiments

The document outlines a series of experiments for a V Semester course on Application Development using Python. It includes tasks such as temperature conversion, calculating student grades, demonstrating sequence data types, and implementing multithreading and GUI applications. Each experiment is accompanied by sample code and expected outputs.

Uploaded by

satya
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)
5 views32 pages

Python Application Development Experiments

The document outlines a series of experiments for a V Semester course on Application Development using Python. It includes tasks such as temperature conversion, calculating student grades, demonstrating sequence data types, and implementing multithreading and GUI applications. Each experiment is accompanied by sample code and expected outputs.

Uploaded by

satya
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

V Semester

Application Development using Python

List of Experiments:

1. Write a menu driven program to convert the given temperature from Fahrenheit to Celsius and
vice versa depending upon user’s choice.

2. Write a python program to calculate total marks, percentage and grade of a student. Marks
obtained in each of the three subjects are to be input by the user. Assign grades according to the
following criteria : Grade A: Percentage >=80 Grade B: Percentage>=70 and 80 Grade C:
Percentage>=60 and =40 and

3. Demonstrate various methods of Sequence Data Types

4. Write a python program to display the first n terms of Fibonacci series.

5. Write a python program to calculate the sum and product of two compatible matrices.

6. Write a function that takes a character and returns True if it is a vowel and False otherwise.

7. Write a program to implement exception handling.

8. Write a program to implement Multithreading

9. Develop a Python GUI calculator using Tkinter

10. Write a Python program to read last 5 lines of a file.

11. Design a simple database application that stores the records and retrieve the same

12. Design a database application to search the specified record from the database.

13. Design a database application to that allows the user to add, delete and modify the records.
1. Write a menu driven program to convert the given temperature from Fahrenheit to Celsius
and vice versa depending upon user’s choice.

def fahrenheit_to_celsius(f):

return (f - 32) * 5 / 9

def celsius_to_fahrenheit(c):

return (c * 9 / 5) + 32

def main():

while True:

print("\nTemperature Conversion Menu:")

print("1. Convert Fahrenheit to Celsius")

print("2. Convert Celsius to Fahrenheit")

print("3. Exit")

choice = input("Enter your choice (1/2/3): ")

if choice == '1':

f = float(input("Enter temperature in Fahrenheit: "))

c = fahrenheit_to_celsius(f)

print(f"{f}°F is {c:.2f}°C")

elif choice == '2':

c = float(input("Enter temperature in Celsius: "))

f = celsius_to_fahrenheit(c)

print(f"{c}°C is {f:.2f}°F")

elif choice == '3':

print("Exiting the program. Goodbye!")

break
else:

print("Invalid choice. Please try again.")

if __name__ == "__main__":

main()

output

Temperature Conversion Menu:

1. Convert Fahrenheit to Celsius

2. Convert Celsius to Fahrenheit

3. Exit

Enter your choice (1/2/3): 1

Enter temperature in Fahrenheit: 23

23.0°F is -5.00°C

Temperature Conversion Menu:

1. Convert Fahrenheit to Celsius

2. Convert Celsius to Fahrenheit

3. Exit

Enter your choice (1/2/3): 2

Enter temperature in Celsius: 32

32.0°C is 89.60°F

Temperature Conversion Menu:

1. Convert Fahrenheit to Celsius

2. Convert Celsius to Fahrenheit

3. Exit

Enter your choice (1/2/3): 3


Exiting the program. Goodbye!

2. Write a python program to calculate total marks, percentage and grade of a student. Marks
obtained in each of the three subjects are to be input by the user. Assign grades according to
the following criteria : Grade A: Percentage >=80 Grade B: Percentage>=70 and 80 Grade C:
Percentage>=60 and =40 and

# Function to calculate grade based on percentage

def calculate_grade(percentage):

if percentage >= 80:

return 'A'

elif percentage >= 70:

return 'B'

elif percentage >= 60:

return 'C'

elif percentage >= 40:

return 'D'

else:

return 'E'

# Input marks for 3 subjects

print("Enter marks for the three subjects (out of 100):")

subject1 = float(input("Subject 1: "))

subject2 = float(input("Subject 2: "))

subject3 = float(input("Subject 3: "))

# Calculate total and percentage

total_marks = subject1 + subject2 + subject3

percentage = total_marks / 3
# Determine grade

grade = calculate_grade(percentage)

# Display results

print("\nResults:")

print(f"Total Marks = {total_marks}/300")

print(f"Percentage = {percentage:.2f}%")

print(f"Grade = {grade}")

output

Enter marks for the three subjects (out of 100):

Subject 1: 80

Subject 2: 90

Subject 3: 75

Results:

Total Marks = 245.0/300

Percentage = 81.67%

Grade = A

3. Demonstrate various methods of Sequence Data Types

# Demonstration of Sequence Data Types in Python

# ===== LIST METHODS =====

print("\n--- LIST METHODS ---")

fruits = ['apple', 'banana', 'cherry']

print("Original list:", fruits)


[Link]('orange')

[Link](1, 'grape')

[Link]('banana')

popped = [Link]()

index = [Link]('apple')

count = [Link]('apple')

[Link]()

[Link]()

copy_fruits = [Link]()

print("Modified list:", fruits)

print("Popped item:", popped)

print("Index of 'apple':", index)

print("Count of 'apple':", count)

print("Copied list:", copy_fruits)

# ===== TUPLE METHODS =====

print("\n--- TUPLE METHODS ---")

colors = ('red', 'green', 'blue', 'red')

print("Tuple:", colors)

print("Index of 'green':", [Link]('green'))

print("Count of 'red':", [Link]('red'))

# ===== STRING METHODS =====

print("\n--- STRING METHODS ---")

text = "hello world"


print("Original string:", text)

print("Uppercase:", [Link]())

print("Lowercase:", [Link]())

print("Capitalized:", [Link]())

print("Replaced:", [Link]("world", "Python"))

print("Split:", [Link]())

print("Joined:", "-".join(['a', 'b', 'c']))

print("Stripped:", " spaced ".strip())

# ===== RANGE =====

print("\n--- RANGE OBJECTS ---")

r1 = range(5)

r2 = range(2, 10, 2)

print("Range r1 (0 to 4):", list(r1))

print("Range r2 (2 to 8 step 2):", list(r2))

# ===== COMMON SEQUENCE OPERATIONS =====

print("\n--- COMMON SEQUENCE OPERATIONS ---")

seq = [1, 2, 3, 4, 5]

print("Original sequence:", seq)

print("Indexing seq[0]:", seq[0])

print("Slicing seq[1:4]:", seq[1:4])

print("Concatenation seq + [6, 7]:", seq + [6, 7])

print("Repetition seq * 2:", seq * 2)

print("Membership test (3 in seq):", 3 in seq)

print("Length of sequence:", len(seq))

output
--- LIST METHODS ---

Original list: ['apple', 'banana', 'cherry']

Modified list: ['grape', 'cherry', 'apple']

Popped item: orange

Index of 'apple': 0

Count of 'apple': 1

Copied list: ['grape', 'cherry', 'apple']

--- TUPLE METHODS ---

Tuple: ('red', 'green', 'blue', 'red')

Index of 'green': 1

Count of 'red': 2

--- STRING METHODS ---

Original string: hello world

Uppercase: HELLO WORLD

Lowercase: hello world

Capitalized: Hello world

Replaced: hello Python

Split: ['hello', 'world']

Joined: a-b-c

Stripped: spaced

--- RANGE OBJECTS ---

Range r1 (0 to 4): [0, 1, 2, 3, 4]

Range r2 (2 to 8 step 2): [2, 4, 6, 8]


--- COMMON SEQUENCE OPERATIONS ---

Original sequence: [1, 2, 3, 4, 5]

Indexing seq[0]: 1

Slicing seq[1:4]: [2, 3, 4]

Concatenation seq + [6, 7]: [1, 2, 3, 4, 5, 6, 7]

Repetition seq * 2: [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

Membership test (3 in seq): True

Length of sequence: 5

4. Write a python program to display the first n terms of Fibonacci series.

# Function to generate Fibonacci series

def fibonacci(n):

a, b = 0, 1

series = []

for _ in range(n):

[Link](a)

a, b = b, a + b

return series

# Input from user

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

# Display Fibonacci series

if n <= 0:

print("Please enter a positive integer.")


else:

print("Fibonacci Series:")

print(fibonacci(n))

output

Enter the number of terms: 6

Fibonacci Series:

[0, 1, 1, 2, 3, 5]

5. Write a python program to calculate the sum and product of two compatible matrices.

# Function to input a matrix

def input_matrix(rows, cols, name):

print(f"Enter elements of Matrix {name} ({rows}x{cols}):")

return [[int(input(f"{name}[{i+1}][{j+1}]: ")) for j in range(cols)] for i in range(rows)]

# Function to add two matrices

def add_matrices(A, B):

return [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in range(len(A))]

# Function to multiply two matrices

def multiply_matrices(A, B):

result = [[0 for _ in range(len(B[0]))] for _ in range(len(A))]

for i in range(len(A)):

for j in range(len(B[0])):

for k in range(len(B)):

result[i][j] += A[i][k] * B[k][j]

return result
# Main program

# Input matrix sizes

rows_A = int(input("Enter number of rows for Matrix A: "))

cols_A = int(input("Enter number of columns for Matrix A: "))

rows_B = int(input("Enter number of rows for Matrix B: "))

cols_B = int(input("Enter number of columns for Matrix B: "))

# Check if addition and multiplication are possible

can_add = rows_A == rows_B and cols_A == cols_B

can_multiply = cols_A == rows_B

# Input matrices

A = input_matrix(rows_A, cols_A, "A")

B = input_matrix(rows_B, cols_B, "B")

# Perform operations

if can_add:

sum_matrix = add_matrices(A, B)

print("\nSum of Matrices A and B:")

for row in sum_matrix:

print(row)

else:

print("\nMatrix addition not possible due to incompatible dimensions.")

if can_multiply:
product_matrix = multiply_matrices(A, B)

print("\nProduct of Matrices A and B:")

for row in product_matrix:

print(row)

else:

print("\nMatrix multiplication not possible due to incompatible dimensions.")

output

Enter number of rows for Matrix A: 2

Enter number of columns for Matrix A: 2

Enter number of rows for Matrix B: 2

Enter number of columns for Matrix B: 2

Enter elements of Matrix A (2x2):

A[1][1]: 2

A[1][2]: 3

A[2][1]: 4

A[2][2]: 5

Enter elements of Matrix B (2x2):

B[1][1]: 2

B[1][2]: 3

B[2][1]: 4

B[2][2]: 5

Sum of Matrices A and B:

[4, 6]

[8, 10]
Product of Matrices A and B:

[16, 21]

[28, 37]

6. Write a function that takes a character and returns True if it is a vowel and False otherwise.

def is_vowel(char):

return [Link]() in 'aeiou'

# Get input from user

ch = input("Enter a character: ")

if len(ch) == 1:

if is_vowel(ch):

print("It is a vowel.")

else:

print("It is not a vowel.")

output

Enter a character: a

It is a vowel.

7. Write a program to implement exception handling.

def divide_numbers():
try:
num1 = int(input("Enter the numerator: "))
num2 = int(input("Enter the denominator: "))
result = num1 / num2
except ValueError:
print("Invalid input! Please enter only integers.")
except ZeroDivisionError:
print(" Cannot divide by zero.")
else:
print(f" Result: {num1} / {num2} = {result}")
finally:
print("Program execution completed.")

# Call the function


divide_numbers()

output

Enter the numerator: 10


Enter the denominator: 2
Result: 10 / 2 = 5.0
Program execution completed.

8. Write a program to implement Multithreading

import threading
import time

# Define the first task


def print_numbers():
for i in range(1, 7):
print(f"Number: {i}")
[Link](1)

# Define the second task


def print_letters():
for letter in ['A', 'B', 'C', 'D', 'E','f']:
print(f"Letter: {letter}")
[Link](1)

# Create threads
thread1 = [Link](target=print_numbers)
thread2 = [Link](target=print_letters)

# Start threads
[Link]()
[Link]()

# Wait for both threads to complete


[Link]()
[Link]()

print(" Both threads have finished execution.")

output
Number: 1Letter: A

Number: 2
Letter: B
Number: 3Letter: C

Number: 4Letter: D

Number: 5
Letter: E
Number: 6Letter: f

Both threads have finished execution.

9. Develop a Python GUI calculator using Tkinter

import tkinter as tk

def click(event):

current = str([Link]())

text = [Link]("text")

if text == "=":

try:

result = eval(current)

[Link](0, [Link])

[Link](0, result)

except Exception as e:

[Link](0, [Link])

[Link](0, "Error")

elif text == "C":

[Link](0, [Link])

else:
[Link]([Link], text)

# Create main window

root = [Link]()

[Link]("Simple Calculator")

[Link]("300x400")

[Link](False, False)

# Entry field

entry = [Link](root, font="Arial 20", borderwidth=5, relief=[Link], justify=[Link])

[Link](padx=10, pady=10, fill=[Link], ipadx=8, ipady=15)

# Button layout

buttons = [

['7', '8', '9', '/'],

['4', '5', '6', '*'],

['1', '2', '3', '-'],

['C', '0', '=', '+']

# Create buttons

for row in buttons:

frame = [Link](root)

[Link](expand=True, fill="both")

for btn in row:

button = [Link](frame, text=btn, font="Arial 18", relief=[Link])


[Link](side="left", expand=True, fill="both", padx=1, pady=1)

[Link]("<Button-1>", click)

# Start GUI event loop

[Link]()

output

10. Write a Python program to read last 5 lines of a file.

def read_last_lines(file_path, num_lines=5):

try:

with open(file_path, 'r') as file:

lines = [Link]()

last_lines = lines[-num_lines:]
return last_lines

except FileNotFoundError:

print(f"File '{file_path}' not found.")

return []

except Exception as e:

print(f"An error occurred: {e}")

return []

file_path = '[Link]' # Replace with your file path

last_5_lines = read_last_lines(file_path)

print("Last 5 lines of the file:")

for line in last_5_lines:

print([Link]())

[Link] file
Python is a versatile, high-level, general-purpose programming language

known for its readability and ease of use.

It's used in various applications, including web development,

data science, software development, and automation.

Object-Oriented Programming:

Python supports object-oriented principles,

making it suitable for developing complex software applications.

Output

Last 5 lines of the file:

data science, software development, and automation.

Object-Oriented Programming:
Python supports object-oriented principles,

making it suitable for developing complex software applications.

11. Design a simple database application that stores the records and retrieve the same

import sqlite3

# Step 1: Connect to a database (or create it if it doesn't exist)

def connect_db():

conn = [Link]('[Link]')

return conn

# Step 2: Create a table

def create_table(conn):

cursor = [Link]()

[Link]('''

CREATE TABLE IF NOT EXISTS people (

id INTEGER PRIMARY KEY AUTOINCREMENT,

name TEXT NOT NULL,

age INTEGER NOT NULL,

email TEXT

''')

[Link]()

# Step 3: Insert a record

def insert_record(conn, name, age, email):

cursor = [Link]()
[Link]('''

INSERT INTO people (name, age, email)

VALUES (?, ?, ?)

''', (name, age, email))

[Link]()

# Step 4: Retrieve and display records

def fetch_records(conn):

cursor = [Link]()

[Link]('SELECT * FROM people')

rows = [Link]()

for row in rows:

print(f"ID: {row[0]}, Name: {row[1]}, Age: {row[2]}, Email: {row[3]}")

# Main menu-driven application

def main():

conn = connect_db()

create_table(conn)

while True:

print("\n--- Simple Database Application ---")

print("1. Add Record")

print("2. View Records")

print("3. Exit")

choice = input("Enter your choice: ")


if choice == '1':

name = input("Enter name: ")

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

email = input("Enter email: ")

insert_record(conn, name, age, email)

print("Record added successfully!")

elif choice == '2':

print("\n--- Stored Records ---")

fetch_records(conn)

elif choice == '3':

print("Exiting the application.")

break

else:

print("Invalid choice. Please try again.")

[Link]()

if __name__ == '__main__':

main()

output

--- Simple Database Application ---

1. Add Record

2. View Records

3. Exit

Enter your choice: 1

Enter name: satya

Enter age: 36
Enter email: satya@[Link]

Record added successfully!

--- Simple Database Application ---

1. Add Record

2. View Records

3. Exit

Enter your choice: 2

--- Stored Records ---

ID: 1, Name: roja, Age: 53, Email: roja@[Link]

ID: 2, Name: lakshmi, Age: 50, Email: lakshmi@[Link]

ID: 3, Name: satya, Age: 36, Email: satya@[Link]

--- Simple Database Application ---

1. Add Record

2. View Records

3. Exit

Enter your choice: 3

Exiting the application.

12. Design a database application to search the specified record from the database.

import sqlite3

# Connect to or create database

def connect_db():

return [Link]('[Link]')
# Create table if it doesn't exist

def create_table(conn):

cursor = [Link]()

[Link]('''

CREATE TABLE IF NOT EXISTS people (

id INTEGER PRIMARY KEY AUTOINCREMENT,

name TEXT NOT NULL,

age INTEGER,

email TEXT

''')

[Link]()

# Insert a new record

def insert_record(conn, name, age, email):

cursor = [Link]()

[Link]('''

INSERT INTO people (name, age, email)

VALUES (?, ?, ?)

''', (name, age, email))

[Link]()

# Search for a record by name

def search_record(conn, search_name):

cursor = [Link]()

[Link]('''

SELECT * FROM people WHERE name = ?


''', (search_name,))

results = [Link]()

if results:

print("\n--- Search Results ---")

for row in results:

print(f"ID: {row[0]}, Name: {row[1]}, Age: {row[2]}, Email: {row[3]}")

else:

print("No matching record found.")

# Main menu

def main():

conn = connect_db()

create_table(conn)

while True:

print("\n--- Database Search Application ---")

print("1. Add Record")

print("2. Search Record by Name")

print("3. Exit")

choice = input("Enter your choice: ")

if choice == '1':

name = input("Enter name: ")

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

email = input("Enter email: ")


insert_record(conn, name, age, email)

print("Record added successfully.")

elif choice == '2':

search_name = input("Enter name to search: ")

search_record(conn, search_name)

elif choice == '3':

print("Exiting application.")

break

else:

print("Invalid choice. Try again.")

[Link]()

if __name__ == '__main__':

main()

output

--- Database Search Application ---

1. Add Record

2. Search Record by Name

3. Exit

Enter your choice: 1

Enter name: satyavathi

Enter age: 35

Enter email: satyasri@[Link]

Record added successfully.


--- Database Search Application ---

1. Add Record

2. Search Record by Name

3. Exit

Enter your choice: 2

Enter name to search: satyavathi

--- Search Results ---

ID: 6, Name: satyavathi, Age: 35, Email: satyasri@[Link]

--- Database Search Application ---

1. Add Record

2. Search Record by Name

3. Exit

Enter your choice: 3

Exiting application.

13. Design a database application to that allows the user to add, delete and modify the records.

import sqlite3

# Connect to or create the database

def connect_db():

return [Link]('[Link]')

# Create the table if it doesn't exist

def create_table(conn):
cursor = [Link]()

[Link]('''

CREATE TABLE IF NOT EXISTS people (

id INTEGER PRIMARY KEY AUTOINCREMENT,

name TEXT NOT NULL,

age INTEGER,

email TEXT

''')

[Link]()

# Add a new record

def add_record(conn, name, age, email):

cursor = [Link]()

[Link]('''

INSERT INTO people (name, age, email)

VALUES (?, ?, ?)

''', (name, age, email))

[Link]()

print("✅ Record added successfully.")

# View all records

def view_records(conn):

cursor = [Link]()

[Link]('SELECT * FROM people')

records = [Link]()

if records:
print("\n--- All Records ---")

for row in records:

print(f"ID: {row[0]}, Name: {row[1]}, Age: {row[2]}, Email: {row[3]}")

else:

print("No records found.")

# Delete a record by ID

def delete_record(conn, record_id):

cursor = [Link]()

[Link]('DELETE FROM people WHERE id = ?', (record_id,))

[Link]()

if [Link]:

print(" Record deleted successfully.")

else:

print(" No record found with that ID.")

# Modify a record by ID

def modify_record(conn, record_id, new_name, new_age, new_email):

cursor = [Link]()

[Link]('''

UPDATE people

SET name = ?, age = ?, email = ?

WHERE id = ?

''', (new_name, new_age, new_email, record_id))

[Link]()

if [Link]:

print("Record updated successfully.")


else:

print("No record found with that ID.")

# Menu-driven interface

def main():

conn = connect_db()

create_table(conn)

while True:

print("\n--- Database Management Application ---")

print("1. Add Record")

print("2. View All Records")

print("3. Delete Record")

print("4. Modify Record")

print("5. Exit")

choice = input("Enter your choice: ")

if choice == '1':

name = input("Enter name: ")

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

email = input("Enter email: ")

add_record(conn, name, age, email)

elif choice == '2':

view_records(conn)

elif choice == '3':

record_id = int(input("Enter ID of the record to delete: "))


delete_record(conn, record_id)

elif choice == '4':

record_id = int(input("Enter ID of the record to modify: "))

new_name = input("Enter new name: ")

new_age = int(input("Enter new age: "))

new_email = input("Enter new email: ")

modify_record(conn, record_id, new_name, new_age, new_email)

elif choice == '5':

print(" Exiting application.")

break

else:

print("Invalid choice. Please try again.")

[Link]()

if __name__ == '__main__':

main()

output

--- Database Management Application ---

1. Add Record

2. View All Records

3. Delete Record

4. Modify Record

5. Exit

Enter your choice: 1

Enter name: kanakalakshmi


Enter age: 40

Enter email: kanaka@[Link]

Record added successfully.

--- Database Management Application ---

1. Add Record

2. View All Records

3. Delete Record

4. Modify Record

5. Exit

Enter your choice: 2

--- All Records ---

ID: 1, Name: roja, Age: 53, Email: roja@[Link]

ID: 2, Name: lakshmi, Age: 50, Email: lakshmi@[Link]

ID: 3, Name: satya, Age: 36, Email: satya@[Link]

ID: 4, Name: hymavathi, Age: 50, Email: hyma@[Link]

ID: 5, Name: nischala, Age: 40, Email: nischala@[Link]

ID: 6, Name: satyavathi, Age: 35, Email: satyasri@[Link]

ID: 7, Name: chaitanya, Age: 35, Email: chaitanya@[Link]

ID: 8, Name: kanakalakshmi, Age: 40, Email: kanaka@[Link]

--- Database Management Application ---

1. Add Record

2. View All Records

3. Delete Record

4. Modify Record
5. Exit

Enter your choice: 3

Enter ID of the record to delete: 3

Record deleted successfully.

--- Database Management Application ---

1. Add Record

2. View All Records

3. Delete Record

4. Modify Record

5. Exit

Enter your choice: 4

Enter ID of the record to modify: 6

Enter new name: satyasri

Enter new age: 35

Enter new email: satyasri@[Link]

Record updated successfully.

--- Database Management Application ---

1. Add Record

2. View All Records

3. Delete Record

4. Modify Record

5. Exit

Enter your choice: 5

Exiting application.

You might also like