0% found this document useful (0 votes)
3 views23 pages

Python Sam(1) Pages

The document outlines a curriculum for the 5th Semester Python Programming course at St Mary’s Group of Institutions, Hyderabad, detailing a comprehensive list of experiments and programs. It includes tasks such as writing programs for control structures, matrix operations, exception handling, and GUI design, as well as using Raspberry Pi for various applications. Each experiment is accompanied by an aim, theory, and sample code to facilitate learning and practical application of Python programming concepts.

Uploaded by

srivatsav1110
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)
3 views23 pages

Python Sam(1) Pages

The document outlines a curriculum for the 5th Semester Python Programming course at St Mary’s Group of Institutions, Hyderabad, detailing a comprehensive list of experiments and programs. It includes tasks such as writing programs for control structures, matrix operations, exception handling, and GUI design, as well as using Raspberry Pi for various applications. Each experiment is accompanied by an aim, theory, and sample code to facilitate learning and practical application of Python programming concepts.

Uploaded by

srivatsav1110
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/ 23

St Mary’s Group of Institutions,

Hyderabad
Department of Computer Science-Diploma
PYTHON PROGRAMMING
5th Semester 2024-2025

List of Experiments

1. Write a python program using control structures

2. Write a python program to find the factorial of a number

3. Write a python program to perform matrix addition and multiplication

4. Write a python programs to make use of tuples, list and dictionary

5. Write a python program which consists of multiple threads

6. Write a python program to handle exception with multiple except statements with single try

7. Write a python program using nested try statements

8. Design Graphical user interface application

9 Design regular expression to validate given text

10. Constructing a PC using Raspberry PI and Board com processor

11. Installation of operating system using Raspberry PI

12. Turning ON/OFF LED with Raspberry PI and Python program

13. Buzzer sound with Raspberry PI and Python program

14. Write a python program for method overloading

15. Write a python program for method overriding


16. Write a python program for multiple inheritance

17. Write a python program for hybrid inheritance

18. Write a python program to perform operations on strings

19. Write a python program to slice a list

20. Write a python program to display multiplication tables

21. Write a python program to achieve thread synchronization in multithreaded environment

22. Design Graphical user interface application using different widgets

23. Design GUI using different Geometry Managers

24. Develop a python program to handle events generated by various widgets

25. Develop a python program to open, close, read, write, and append data into the files

26. Develop a python program to connect to MySql database

27. Develop a python program for creation of table, insert a row in a table, update an entry in a
table

28. Develop a python program to execute stored procedures

29. Develop a python program to store images using blob data type
Programs
1. Write a program using control structures?
Aim: To write a program using control structures in Python

Theory: Printing prime numbers using control structures. Prime number is a


number that is divisible by one and itself

Experiment:

def is_prime(x):

prime = True

if (x < 2):

prime = True

else:

for i in range(2,x):

if x%i == 0:

prime = False break

return prime

def display_primes(n):

for i in range(n):

if is_prime(i):

print(i)

if name ==" main ":

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

display_primes(n)
Output:

Enter a number:20 0

11

13

17

19
2. Write a program to find the factorial of a number?
Aim: To find the factorial of a number

Theory: The factorial of a non-negative integer n, denoted asn!, is the


product of all positive integers less than or equal to n. Mathematically, it is
defined as:

n!=n×(n−1)×(n−2)×…×3×2×1

Program:

def factorial_recursive(n): if

n == 0 or n == 1:

return 1

else:

return n * factorial_recursive(n - 1) #take

inputs here

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

factorial_recursive(number) print(f"The

factorial of {number} is: {result}")

Output:

Enter a number:5

The factorial of 5 is: 120


3. Write a python program to perform matrix addition and
multiplication
3.1 Write a python program to perform matrix addition

Aim: To write a program to find the additions

Theory: Matrix addition is a mathematical operation that combines two


matrices to create a new matrix. To add two matrices, they must have the
same dimensions, meaning they must have the same number of rows and
columns. The resulting matrix will also have the same dimensions.

Program:

# Program to add two matrices using nested loop

X = [[12,7,3],

[4 ,5,6],

[7 ,8,9]]

Y = [[5,8,1],

[6,7,3],

[4,5,9]]

result = [[0,0,0],

[0,0,0],

[0,0,0]]

# iterate through rows for

i in range(len(X)):

# iterate through columns

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

result[i][j] = X[i][j] + Y[i][j]


for r in result:

print(r)

Output:

[17, 15, 4]

[10, 12, 9]

[11, 13, 18]


3.2. Write a python program to perform matrix multiplication

Aim: To write a python program to perform matrix multiplication

Theory: Matrix multiplication is a binary operation that takes a pair of


matrices and produces another matrix. Unlike addition, matrix multiplication
is defined for matrices of arbitrary sizes, but there are specific rules
regarding the dimensions of the matrices involved.

Program:

# Program to multiply two matrices using nested loops

# 3x3 matrix

X = [[12,7,3],

[4 ,5,6],

[7 ,8,9]]

# 3x4 matrix

Y = [[5,8,1,2],

[6,7,3,0],

[4,5,9,1]]

# result is 3x4

result = [[0,0,0,0],

[0,0,0,0],

[0,0,0,0]]

# iterate through rows of X for

i in range(len(X)):

# iterate through columns of Y for

j in range(len(Y[0])):
# iterate through rows of Y for

k in range(len(Y)):

result[i][j] += X[i][k] * Y[k][j]

for r in result:

print(r)

Output:

[114, 160, 60, 27]

[74, 97, 73, 14]

[119, 157, 112, 23]


4. Write a program to make tuples, list and dictionary
Aim :To write a program to make tuples, list and dictionary

Theory: Tuples, lists and dictionaries are three data structures used in
python

Program:

# Tuple example

my_tuple = (1, 2, 3, 4, 5) # Creating a tuple

# List example

my_list = ['apple', 'banana', 'orange', 'grape'] # Creating a list

# Dictionary example

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'} # Creating a


dictionary

# Modifying elements in list

my_list[1] = 'pineapple' # Modifying the second element of the list

print("Modified List:", my_list)

# Adding a new key-value pair in dictionary

my_dict['occupation'] = 'Engineer' print("Updated

Dictionary:", my_dict)

# Iterating through elements in list

print("Iterating through List:")

for fruit in my_list:

print(fruit)

# Iterating through elements in tuple


print("Iterating through Tuple:")

for num in my_tuple:

print(num)

# Iterating through elements in dictionary

print("Iterating through Dictionary:")

for key, value in my_dict.items():

print(f"{key}: {value}")

Output:

Modified List: ['apple', 'pineapple', 'orange', 'grape']

Updated Dictionary: {'name': 'John', 'age': 30, 'city': 'New York', 'occupation':
'Engineer'} Iterating

through List:

apple

pineapple

orange grape

Iterating through Tuple:

Iterating through Dictionary:


name: John

age: 30

city: New York

occupation: Engineer
5. Write a program which consists of multiple threads
Aim: To write a program using multiple threads

Program:

import threading

import time

# Function to print numbers

def print_numbers():

for i in range(1, 6):

time.sleep(1) # Simulating some work

print(f"Thread 1: {i}")

# Function to print letters def

print_letters():

for letter in 'ABCDE':

time.sleep(0.8) # Simulating some work

print(f"Thread 2: {letter}")

# Create threads

thread1 = threading.Thread(target=print_numbers) thread2 =

threading.Thread(target=print_letters)

# Start threads

thread1.start()

thread2.start()

# Wait for threads to finish

thread1.join() thread2.join()
print("Both threads have finished.")

Output:

Thread 2: A

Thread 1: 1

Thread 2: B

Thread 1: 2

Thread 2: C

Thread 1: 3

Thread 2: D

Thread 1: 4

Thread 2: E

Thread 1: 5

Both threads have finished.


6. Write a program to handle exceptions with multiple except
statements with single try
Aim: To write a program to handle exceptions with multiple except
statements with single try

Program:

def divide_numbers(x, y): try:

result = x / y

print(f"Result of division: {result}")

except ZeroDivisionError:

print("Error: Division by zero is not allowed") except

TypeError:

print("Error: Unsupported operation or invalid data type") except

Exception as e:

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

print("Division operation completed successfully")

finally:

print("End of division function")

# Test cases

divide_numbers(10, 2) # Division without error

print("---")

divide_numbers(10, 0) # Division by zero

print("---")

divide_numbers(10, '2') # Invalid operation (TypeError)


print("---")

divide_numbers(10, []) # Some other unexpected error

Output:

Result of division: 5.0

Division operation completed successfully

End of division function

---

Error: Division by zero is not allowed End

of division function

---

Error: Unsupported operation or invalid data type End of

division function

---

Error: Unsupported operation or invalid data type End of

division function
7. Write a program using nested try statement
Aim :To write a program using nested try statement

Program:

def nested_try_example(): try:

# Outer try block

number_str = input("Enter a number: ")

number = int(number_str)

try:

# Inner try block

result = 10 / number

print(f"Result of division: {result}")

except ZeroDivisionError:

print("Error: Division by zero in the inner try block")

except ValueError:

print("Error: Invalid input. Please enter a valid number.")

except Exception as e:

print(f"An error occurred in the outer try block: {e}")

finally:

print("End of the program")

# Test the nested try statement program

nested_try_example()
Output:

Enter a number: 0

Error: Division by zero in the inner try block End

of the program

Enter a number: 5 Result

of division: 2.0 End of

the program

Enter a number: a

Error: Invalid input. Please enter a valid number. End of the program
8. Design a Graphical User Interface application
Aim: To Design a Graphical User Interface application

Program:

import tkinter as tk

def calculate():

"""Function to perform calculation."""

try:

# Get the input values from entry widgets

num1 = float(entry_num1.get())

num2 = float(entry_num2.get())

operator = entry_operator.get()

# Perform the calculation based on the operator

if operator == '+':

result = num1 + num2

elif operator == '-':

result = num1 - num2

elif operator == '*':

result = num1 * num2

elif operator == '/':

result = num1 / num2

# Display the result entry_result.delete(0, tk.END)


entry_result.insert(0, result)

except ValueError:

entry_result.delete(0, tk.END)

entry_result.insert(0, "Error")

# Create the main window

window = tk.Tk()

window.title("Simple Calculator")

# Create input widgets

entry_num1 = tk.Entry(window)

entry_num1.grid(row=0, column=0)

entry_operator = tk.Entry(window)

entry_operator.grid(row=0, column=1)

entry_num2 = tk.Entry(window)

entry_num2.grid(row=0, column=2)

# Create button to perform calculation

btn_calculate=tk.Button(window,text="Calculate",command=calculate)
btn_calculate.grid(row=0, column=3)
# Create entry widget to display result

entry_result = tk.Entry(window)

entry_result.grid(row=1, column=0, columnspan=4)

# Start the GUI event loop window.mainloop()

Output:
9. Design a regular Expression to Validate a given Text
Aim: To Design a regular Expression to Validate a given Text

Program:

import re # Import the regular expression module

def validate_text(text):

"""Function to validate text using regular expressions."""

pattern = r'^[a-zA-Z0-9_-]+$' # Define a regular expression pattern

# The pattern ^[a-zA-Z0-9_-]+$ matches strings that contain only


alphanumeric characters, underscores, and hyphens

# ^ asserts the start of the string

# [a-zA-Z0-9_-] matches any alphanumeric character, underscore, or


hyphen

# + matches one or more occurrences of the preceding character class

# $ asserts the end of the string

if re.match(pattern, text): # Use the match function from the re module to


check if the text matches the pattern

return True # Return True if the text matches the pattern

else:

return False # Return False if the text does not match the pattern

# Example usage:

text_to_validate = "Hello123"

# The text to be validated


if validate_text(text_to_validate): # Call the validate_text function with the
text to validate print("Text is valid!") # Print a message indicating that the
text is valid if the function returns True

else:

print("Text is not valid!") # Print a message indicating that the text is not
valid if the function returns False

Output:

Text is valid!

You might also like