0% found this document useful (0 votes)
9 views41 pages

Python Programming Lab Exercises

The document outlines a Python Programming Lab for III B.Sc Computer Science students, detailing various programming tasks including creating a simple calculator, using control flow tools, and implementing data structures. It includes specific aims, procedures, and sample code for each task, covering topics such as exception handling, file operations, and database connectivity. The lab aims to enhance students' practical programming skills through hands-on exercises.

Uploaded by

saravanan.mgk
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)
9 views41 pages

Python Programming Lab Exercises

The document outlines a Python Programming Lab for III B.Sc Computer Science students, detailing various programming tasks including creating a simple calculator, using control flow tools, and implementing data structures. It includes specific aims, procedures, and sample code for each task, covering topics such as exception handling, file operations, and database connectivity. The lab aims to enhance students' practical programming skills through hands-on exercises.

Uploaded by

saravanan.mgk
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

PYTHON PROGRAMMING LAB

SUBJECT CODE : 20UCS6CP6


CLASS : III [Link] COMPUTER SCIENCE

SEMESTER : SIXTH SEMESTER

PREPARED BY
[Link] [Link]., [Link]. [Link]

Assistant Professor / Department of Computer Science,

Thanthani Hans Roever College (A),

Elambalur, Perambalur-621220
CONTENTS
[Link] Title of the Program

Simple Calculator to do All the Arithmetic


1
Operations

2(a) Program to Use Control Flow Tools Like If


2(b) While Statement

3 Nested for loop to print the following pattern

Data structures use list as stack use list as queue


4
tuple, sequence

Create new module for mathematical operations


5
and use in your program

Write a program to read and write files, create and


6
delete directories

7 Program with Exception Handling

8 Write a program using classes

9 Connect with MySQL and create address book

Program Using String Handling and Regular


10
Expressions

11 Program to parse apache log file

GUI program using pygtk


12
1. Simple Calculator to do All the Arithmetic Operations

Aim: To create a Simple Calculator to do All the Arithmetic Operations


Procedure:

Step 1: Define the functions for addition, subtraction, multiplication, division, and modulus
calculations.

Step 2: Prompt the user to select the desired operation from a list (1 for addition, 2 for
subtraction, and so on).

Step 3: Take input from the user for two numbers to perform the chosen operation on.

Step 4: Based on the user's choice, execute the corresponding function.

Step 5: Print the result of the operation.

Step 6: Handle division by zero case for the division and modulus operations.

Step 7: Inform the user if an invalid input is provided.


Program:

# Addition
def addition(n1, n2):
return n1 + n2
# Subtraction
def subtraction(n1, n2):
return n1 - n2
# Multiplication
def multiplication(n1, n2):
return n1 * n2
# Division
def division(n1, n2):
return n1 / n2
# modulus
def modulus(n1, n2):
if n2 != 0:
return n1 % n2
else:
return "Cannot calculate modulus with zero divisor"

print("Select Operations")
print(
"1. Addition\n"
"2. Subtraction\n"
"3. Multiplication\n"
"4. Division\n"
"5. modulus\n")

# Giving the option to the user to choose the operation


operation = int(input("Enter choice of operation 1/2/3/4/5: "))
#Taking Input from the Users
n1 = float(input("Enter the First Number: "))
n2 = float(input("Enter the Second Number: "))

# Apply Conditional Statements: To make operation as-per-user choices

if operation == 1:
print (n1, "+", n2, "=", addition(n1, n2))

elif operation == 2:
print (n1, "-", n2, "=", subtraction(n1, n2))

elif operation == 3:
print (n1, "*", n2, "=", multiplication(n1, n2))

elif operation == 4:
print (n1, "/", n2, "=", division(n1, n2))

elif operation == 5:
print (n1, "%", n2, "=",modulus(n1,n2))
else:
print("Invalid Input")

OUTPUT:
Select Operations
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. modulus
Enter choice of operation 1/2/3/4/5: 1
Enter the First Number: 8
Enter the Second Number: 9
8.0 + 9.0 = 17.0

Enter choice of operation 1/2/3/4/5: 2


Enter the First Number: 5
Enter the Second Number: 3
5.0 - 3.0 = 2.0

Enter choice of operation 1/2/3/4/5: 3


Enter the First Number: 5
Enter the Second Number: 2
5.0 * 2.0 = 10.0

Enter choice of operation 1/2/3/4/5: 4


Enter the First Number: 10
Enter the Second Number: 2
10.0 / 2.0 = 5.0

Enter choice of operation 1/2/3/4/5: 5


Enter the First Number: 10
Enter the Second Number: 2
10.0 % 2.0 = 0.0
2. PROGRAM TO USE CONTROL FLOW TOOLS LIKE IF

Aim:
To write a program to use control flow tools.
Procedure:
Step 1: Prompt the user to enter a number.
Step 2: Initialize a variable is prime to True.
Step 3: Iterate over a range from 2 to one less than the input number.
Step 4: Check if the input number is divisible by any number in the range (from 2 to one less
than the number).
Step 5: If the input number is divisible by any number in the range, set is prime to False and
break the loop.
Step 6: After the loop, if is_prime is still True, print that the number is prime.
Step 7 : Otherwise, if is prime is False, print that the number is not prime.
Program:

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


is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
print("%d is prime number" % num)
else:
print("%d is not a prime number" % num)

OUTPUT:
Enter number: 3
3 is prime number

Enter number: 8
8 is not a prime number
2. (1) WHILE STATEMENT

Aim:

To write a program to use control flow tools using while statement

Procedure:

Step 1: Initialize a variable count to 1.

Step 2: Enter a while loop that continues as long as count is less than or equal to 5.

Step 3: Within the loop, print the current value of count.

Step4: Increment the value of count by 1 in each iteration.

Step 5: Once the loop exits (when count exceeds 5), print "End of the program".
Program:
count = 1
while count <= 5:
print("Count:", count)
count += 1
print("End of the program")

OUTPUT:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
End of the program
3. Nested for loop to print the following pattern

Aim:
To write a program to use for loop.
Procedure:
1. Set the variable rows to 5.
2. Execute an outer loop ranging from 1 to rows.
3. Within the outer loop, execute an inner loop ranging from 1 to the current value of i.
4. Inside the inner loop, print an asterisk (*) with a space as the end character.
5. After printing all asterisks for the current row, print a newline character to move to the next
line.
6. Create a list numbers containing integers 1 through 5.
7. Iterate through each element num in the numbers list.
8. Multiply each num by 2 and print the result.
9. Import the string module.
10. Generate uppercase alphabets using `
Program :

rows = 5
# outer loop
for i in range(1, rows + 1):
# inner loop
for j in range(1, i + 1):
print("*", end=" ")
print('')

numbers=[1,2,3,4,5]
for num in numbers:
result= num * 2
print(result)

import string
alphabet=string.ascii_uppercase
for letter in alphabet:
print(letter)
OUTPUT:
*
**
***
****
*****
2
4
6
8
10
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
4. Data structures use list as stack use list as queue tuple, sequence
Aim:
To write a program to data structures use list as stack use list as queue tuple, sequence

Procedure:
1. Initialize an empty list named stack to represent the stack data structure.
2. Push elements onto the stack by using the append() method:
•Append the integer 1 to the stack.
•Append the integer 2 to the stack.
•Append the integer 3 to the stack.
3. Pop elements from the stack using the pop() method:
•Pop the topmost element from the stack and assign it to the variable popped_item.
4. Print the popped item to show which item was removed from the stack.
5. Print the current state of the stack after popping:
•Display the remaining elements in the stack.
Program:
# Stack using list
stack = []

# Push elements onto the stack


[Link](1)
[Link](2)
[Link](3)

# Pop elements from the stack


popped_item = [Link]()
print("Popped item:", popped_item)

# Current state of the stack


print("Stack:", stack)

OUTPUT:
Popped item: 3
Stack: [1, 2]
Aim:

To write a program to data structures use list as stack use list as queue tuple, sequence
Procedure:
1. Import the deque class from the collections module.
2. Initialize an empty list named queue to represent the queue data structure.
3. Enqueue elements into the queue by using the append () method:
•Append the integer 1 to the queue.
•Append the integer 2 to the queue.
•Append the integer 3 to the queue.
4. Dequeue elements from the queue by using the pop(0) method:
•Remove and retrieve the first element (index 0) from the queue and assign it to the
variable dequeued_item.
5. Print the dequeued item to show which item was removed from the front of the queue.
6. Print the current state of the queue after dequeuing:
•Display the remaining elements in the queue.
Program :
from collections import deque
# Queue using list
queue = []
# Enqueue elements
[Link](1)
[Link](2)
[Link](3)
# Dequeue elements
dequeued_item = [Link](0)
print("Dequeued item:", dequeued_item)
# Current state of the queue
print("Queue:", queue)

OUTPUT:
Dequeued item: 1
Queue: [2, 3]
Aim:
To write a program to data structures use list as stack use list as queue tuple, sequence
Procedure:
1. Define a tuple named my_tuple containing the integers 1 through 5.
2. Access elements of the tuple:
•Print the first element of the tuple using index 0.
•Print the last element of the tuple using negative index -1.
3. Iterate over the elements of the tuple using a for loop:
•For each item in the my_tuple, print the item.
Program :

# Tuple as a sequence
my_tuple = (1, 2, 3, 4, 5)

# Access elements
print("First element:", my_tuple[0])
print("Last element:", my_tuple[-1])

# Iterate over the tuple


for item in my_tuple:
print(item)

OUTPUT:

First element: 1
Last element: 5
1
2
3
4
5
5. Create new module for mathematical operations and use in your program
Aim:
To create new module for mathematical operations and use in your program.
Procedure:
1. Define four functions: add sub, prod, and div, each performing addition, subtraction,
multiplication, and division operations respectively.
2. Import all functions (add, sub, prod, div) from the ss module.
3. Assign values 24 to variable a and 3 to variable b.
4. Print the result of calling each function with arguments a and b:
•Print the result of adding a and b.
•Print the result of subtracting b from a.
•Print the result of multiplying a and b.
•Print the result of dividing a by b.
Program :
def add(x,y):
return x + y
def sub(x, y):
return x - y
def prod(x, y):
return x * y
def div(x, y):
return x / y
NEW MODULE
from ss import *
a = 24
b=3
print(add(a,b))
print(sub(a,b))
print(prod(a,b))
print(div(a,b))
OUTPUT:
27
21
72
8.0
6. Write a program to read and write files, create and delete directories
Aim:
TO write a program to read and write files, create and delete directories.
Procedure:
1. Import the os module for file and directory operations.
2. Define four functions: write_to_file, read_from_file, create_directory, and delete_directory,
for writing to files, reading from files, creating directories, and deleting directories respectively.
3. Implement error handling using try-except blocks for file and directory operations to catch
potential exceptions.
4. Provide example usage of the defined functions:
•Write content to a file named '[Link]' using write_to_file.
•Read content from the file '[Link]' using read_from_file.
•Create a directory named 'example_directory' using create_directory.
•Delete the directory 'example_directory' using delete_directory.
Program:
import os

def write_to_file(file_path, content):


try:
with open(file_path, 'w') as file:
[Link](content)
print(f"Content successfully written to {file_path}")
except Exception as e:
print(f"Error writing to file: {e}")

def read_from_file(file_path):
try:
with open(file_path, 'r') as file:
content = [Link]()
print(f"Content read from {file_path}:\n{content}")
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
except Exception as e:
print(f"Error reading from file: {e}")

def create_directory(directory_path):
try:
[Link](directory_path)
print(f"Directory '{directory_path}' created successfully.")
except FileExistsError:
print(f"Error: Directory '{directory_path}' already exists.")
except Exception as e:
print(f"Error creating directory: {e}")

def delete_directory(directory_path):
try:
[Link](directory_path)
print(f"Directory deleted: {directory_path}")
except FileNotFoundError:
print(f"Directory not found: {directory_path}")
except OSError as e:
print(f"Error: {e}")

# Example usage
file_path = '[Link]'
directory_path = 'example_directory'

write_to_file(file_path, 'Hello, this is a sample content.')

read_from_file(file_path)

create_directory(directory_path)

delete_directory(directory_path)

OUTPUT:

Content successfully written to [Link]


Content read from [Link]:
Hello, this is a sample content.
Directory 'example directory' created successfully.
Directory deleted: example directory
7. Program with Exception Handling

Aim:
To write a program with exception handling.
Procedure:
1. Try to convert the user input to an integer and assign it to the variable table.
2. Handle the Value Error exception if the user input cannot be converted to an integer, and print
an error message.
3. If no exception occurs, check if the value of table is between 1 and 12 (inclusive).
4. If the value of table is within the valid range, iterate through numbers from 1 to 10 using a
for loop:
•Print the multiplication table for the specified table up to 10.
5. If the value of table is outside the valid range, print an error message indicating that
multiplication tables can only be generated from 1 to 12.
Program :
try:
table = int(input("Which multiplication times table do you want to print? (Choose from 1 to
12) "))
x = table
except ValueError:
print("ERROR: Enter a whole number.")
else:
if 1 <= table <= 12:
for y in range(1, 11): # Use 11 to print up to 10, as range is exclusive on the upper bound
print(f"{x} * {y} = {x * y}")
else:
print("ERROR: Multiplication tables can be generated from 1 to 12 only.")

OUTPUT:
Which multiplication times table do you want to print? (Choose from 1 to 12) 4
4*1=4
4*2=8
4 * 3 = 12
4 * 4 = 16
4 * 5 = 20
4 * 6 = 24
4 * 7 = 28
4 * 8 = 32
4 * 9 = 36
4 * 10 = 40
8. Write a program using classes
Aim:
To write a program using classes
Procedure:
1. Define a class named Person with a constructor method __init__ that initializes the attributes
name and age.
2. Implement a method get_details () within the class to return a formatted string containing the
person's name and age.
3. Check if the script is being run directly (__name__ == "__main__").
4. Prompt the user to input their name and age.
5. Convert the user input for age to an integer.
6. Create an instance of the Person class with the provided name and age.
7. Print the details of the person by calling the get_details() method of the instance created.
Program:

class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

def get_details(self):
return f"Name: {[Link]}, Age: {[Link]}"

if __name__ == "__main__":
# Creating instances of the Person class
name = input("Enter your name: ")
age = int(input("Enter your age: "))

# Creating an instance of the Person class with user input


person = Person(name, age)

# Accessing attributes and calling methods


print(person.get_details())

OUTPUT:

Enter your name: SREE


Enter your age: 10
Name: SREE, Age: 10
9. Connect with MySQL and create address book
Aim:
TO write a program to Connect with MySQL and create address book.

Procedure:
1. Create Address Book Function:
•Establish a connection to the MySQL database.
•Create a cursor object to interact with the database.
•Define and execute a SQL query to create an address book table if it doesn't exist.
•Commit the changes to the database.
•Close the cursor and the database connection.
2. Add Contact Function:
•Establish a connection to the MySQL database.
•Create a cursor object to interact with the database.
•Define and execute a SQL query to insert a new contact into the address book table.
•Commit the changes to the database.
•Close the cursor and the database connection.
3. Main Function:
•Call the create_address_book() function to create the address book table.
•Add a contact to the address book using the add_contact() function.
Program:
import [Link]

def create_address_book():
# Connect to MySQL
connection = [Link](
host="localhost",
user="root",
password="",
database="sree"
)

# Create a cursor object to interact with the database


cursor = [Link]()

# Create the address book table if it doesn't exist


create_table_query = """
CREATE TABLE IF NOT EXISTS address_book (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
email VARCHAR(255),
phone_number VARCHAR(15)
)
"""
[Link](create_table_query)

# Commit the changes and close the connection


[Link]()
[Link]()
[Link]()

def add_contact(first_name, last_name, email=None, phone_number=None):


# Connect to MySQL
connection = [Link](
host="localhost",
user="root",
password="",
database="sree"
)

# Create a cursor object to interact with the database


cursor = [Link]()

# Insert a new contact into the address book


insert_query = """
INSERT INTO address_book (first_name, last_name, email, phone_number)
VALUES (%s, %s, %s, %s)
"""
values = (first_name, last_name, email, phone_number)
[Link](insert_query, values)

# Commit the changes and close the connection


[Link]()
[Link]()
[Link]()

if __name__ == "__main__":
create_address_book()

# Example: Add a contact to the address book


add_contact("John", "Doe", "[Link]@[Link]", "555-1234")
OUTPUT:

mysql> use sree;

Database changed

mysql> show tables;

+----------------+

| Tables_in_sree |

+----------------+

| address_book |

+----------------+

1 row in set (0.00 sec)

mysql> select * from address_book;

+----+------------+-----------+----------------------+--------------+

| id | first_name | last_name | email | phone_number |

+----+------------+-----------+----------------------+--------------+

| 1 | John | Doe | [Link]@[Link] | 555-1234 |

+----+------------+-----------+----------------------+--------------+

1 row in set (0.00 sec)


10. Program Using String Handling and Regular Expressions
Aim:
To write a Program Using String Handling and Regular Expressions
Procedure:
1. Import the re module for regular expression operations.
2. Define a string named sentence containing a simple sentence.
3. Split the sentence into words using the split() method and count the number of words.
4. Print the count of words in the sentence.
5. Use the [Link]() function to find all occurrences of the letter 's' in the sentence using a
regular expression pattern.
6. Print the count of occurrences of the letter 's'.
7. Use the [Link] () function to substitute all occurrences of the word "is" with "was" in the
sentence using a regular expression pattern.
8. Print the modified sentence.
Program:

import re
sentence = "This is a simple sentence."

words = len([Link]())
print(f"The sentence has {words} words.")

matches = [Link](r"s", sentence)


print(f"The letter 's' appears {len(matches)} times.")

new_sentence = [Link](r"is", "was", sentence)


print(f"The modified sentence is: {new_sentence}")

OUTPUT:
The sentence has 5 words.
The letter 's' appears 4 times.
The modified sentence is: Thwas was a simple sentence.
[Link] to parse apache log file
Aim:
To write a Program to parse apache log file
Procedure:
1. Import the re module for regular expression operations.
2. Define a function named parse_apache_log that takes a log entry string as input.
3. Define a regular expression pattern using [Link]() to match Apache log format.
4. Match the pattern against the log entry using [Link](log_entry).
5. If a match is found, extract the relevant information using [Link]() and return it.
6. If no match is found, return None.
7. Use the parse_apache_log() function to parse a sample log entry.
8. If parsed information is available, print the IP address, HTTP method, path, and status code.
9. If no parsed information is available, print "Log entry not matched."
Program:

import re
def parse_apache_log(log_entry):
# Define a regular expression pattern for Apache log format
pattern = [Link](r'(?P<ip>[\d\.]+) - - \[.*\] "(?P<method>\w+) (?P<path>[\S]+) .*"
(?P<status>\d+)')

# Match the pattern against the log entry


match = [Link](log_entry)

# If a match is found, extract and return the relevant information


if match:
return [Link]()
else:
return None

# Example usage:
log_entry = '[Link] - - [23/Dec/2023:12:34:56 +0000] "GET /example/path HTTP/1.1" 200'

parsed_info = parse_apache_log(log_entry)

if parsed_info:
print("Parsed Log Information:")
print(f"IP Address: {parsed_info['ip']}")
print(f"HTTP Method: {parsed_info['method']}")
print(f"Path: {parsed_info['path']}")
print(f"Status Code: {parsed_info['status']}")
else:
print("Log entry not matched.")
OUTPUT:
Parsed Log Information:
IP Address: [Link]
HTTP Method: GET
Path: /example/path
Status Code: 200
12. GUI program using pygtk
Aim:
To write a program to create a GUI program using pygtk.
Procedure:
1. Import the tkinter module and the messagebox sub module.
2. Define a function on_button_click() that displays an information message box when a button
is clicked.
3. Create the main window using [Link]() and set its title to "Simple GUI Program".
4. Create a label widget with the text "Hello, this is a GUI program." and pack it into the main
window with some padding.
5. Create a button widget with the text "Click Me" and set its command to call the
on_button_click() function.
6. Pack the button widget into the main window with some padding.
7. Start the event loop by calling [Link] (), which waits for user interactions and
handles events such as button clicks.
Program:

import tkinter as tk
from tkinter import messagebox

def on_button_click():
[Link]("Hello", "Welcome to the GUI program!")

# Create the main window


window = [Link]()
[Link]("Simple GUI Program")

# Create a label
label = [Link](window, text="Hello, this is a GUI program.")
[Link](pady=10)

# Create a button
button = [Link](window, text="Click Me", command=on_button_click)
[Link](pady=10)

# Run the main loop


[Link]()
OUTPUT:

You might also like