THANTHAI HANS ROEVER COLLEGE (AUTONOMOUS)
(Affiliated to Bharathidasan University)
Accredited with ‘A’Grade by NAAC (3rd cycle) with CGPA 3.23 out of 4
ELAMBALUR, PERAMBALUR - 621 220.
ADVANCED PYTHON PROGRAMMING LAB
SUBJECT CODE : 25PCS1CP1
CLASS : I [Link] Computer Science
SEMESTER : FIRST SEMESTER
PREPARED BY
[Link] [Link]., [Link]. [Link]
Assistant Professor / Department of Computer Science,
Thanthani Hans Roever College (A),
Elambalur, Perambalur-621220
[Link] using Variables, Constants and I/O Statements in Python
AIM:
To write a python program that demonstrates the use of variables, constants and input/output
statements
ALGORITHM:
Step 1: Start the program
Step 2: Declare and initialize the variables
Step 3: Assign a constant value using a variable(by convention use uppercase)
Step 4: Prompt user for input using input() and convert type if needed(int/float)
Step 5: Store input in variables
Step 6: Perform any simple computation or assignment using variable/constants
Step 7: Display the output using print( ) Step 8: Stop the program
Program
MAX_MARKS = 100
name = input("Enter student name: ")
subject1 = float(input("Enter marks for Subject 1: "))
subject2 = float(input("Enter marks for Subject 2: "))
subject3 = float(input("Enter marks for Subject 3: "))
total = subject1 + subject2 + subject3
average = total / 3
if average >= 90:
grade = "A"
elif average >= 75:
grade = "B"
elif average >= 50:
grade = "C"
else:
grade = "Fail"
print("\n--- STUDENT REPORT ---")
print("Name :", name)
print("Total Marks :", total, "/", MAX_MARKS * 3)
print("Average :", average)
print("Grade :", grade)
OUTPUT:
Enter student name: Shree
Enter marks for Subject 1: 87
Enter marks for Subject 2: 89
Enter marks for Subject 3: 98
--- STUDENT REPORT ---
Name : Shree
Total Marks : 274.0 / 300
Average : 91.33333333333333
Grade :A
RESULT:
The program was executed successfully and it demonstrated the use variables,
constants, input and output statements in python.
[Link] using Operators in python
AIM:
To write a python program that demonstrate the arithmetic operations
ALGORITHM:
Step 1: Start the program
Step 2: To read the two numbers from the user
Step 3: To convert the inputs to appropriate numeric types
Step 4: To compute the arithmetic operations like addition, subtraction, multiplication,
division and modulus
Step 5: To display the computed output using print()
Step 6: Stop the program
Program
def addition(n1,n2):
return n1+n2
def subtraction(n1,n2):
return n1-n2
def multiplication(n1,n2):
return n1*n2
def division(n1,n2):
return n1/n2
def modulus(n1,n2):
if n2!=0:
return n1%n2
else:
return"cannot claculate modulus with zero divisor"
print("select operations")
print(
"[Link]\n"
"[Link]\n"
"[Link]\n"
"[Link]\n"
"[Link]\n")
operation=int(input("Enter choice of operation1\2\3\4\5:"))
n1=float(input("Enter the first Number:"))
n2=float(input("Enter the second Number:"))
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
[Link]
[Link]
[Link]
[Link]
[Link]
Enter choice of operation1\2\3\4\5:1
Enter the first Number:7
Enter the second Number:6
7.0 + 6.0 = 13.0
RESULT:
The program was executed successfully and it demonstrated the arithmetic operator
in python.
[Link] using conditional statements, looping and jump statement
AIM:
To demonstrate the use of conditional statements, loops and jump statements in
python
ALGORITHM:
Step 1: Start the program
Step 2: To read the input from the user or set the initial values
Step 3: To use conditional statements (if,elif,else) to choose the appropriate branch
Step 4: To implement the for loop for iteration
Step 5: To use jump statement(break to exit early when condition is met, Continue to skip to
next iteration when required) inside loops
Step 6: After loop &conditions to prepare final outputs
Step 7: To display the output using print( )
Step 8: Stop the program
Program
print("=== SIMPLE CALCULATOR ===")
print("options: ")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Exit")
while True: # Loop until user exits
choice = int(input("\nEnter your choice (1-5): "))
if choice == 5:
print("Exiting the calculator. Goodbye!")
break
if choice < 1 or choice > 5:
print("Invalid choice! Please select from 1 to 5.")
continue # Skip to next loop iteration
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == 1:
result = num1 + num2
print("Result =", result)
elif choice == 2:
result = num1 - num2
print("Result =", result)
elif choice == 3:
result = num1 * num2
print("Result =", result)
elif choice == 4:
if num2 == 0:
print("Error: Division by zero!")
else:
result = num1 / num2
print("Result =", result)
OUTPUT:
=== SIMPLE CALCULATOR ===
options:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice (1-5): 1
Enter first number: 6
Enter second number: 5
Result = 11.0
Enter your choice (1-5): 2
Enter first number: 6
Enter second number: 5
Result = 1.0
Enter your choice (1-5): 5
Exiting the calculator. Goodbye!
RESULT:
The program was executed successfully and it demonstrated the conditional statement
, loop and jump statement in python
4. Program using Functions and Recursion
AIM:
To define the use of functions and recursive functions in python.
ALGORITHM:
Step 1: Start the program
Step 2: To define a function for a specific task
Step 3: To define a recursive function with a base case and recursive case that calls the same
function with smaller input
Step 4: To read the input from the user using input ( )
Step 5: To call the function and store the result
Step 6: To display the output using print( )
Step 7: Stop the program
Program
def factorial(n):
if n == 0 or n == 1:
return 1 # Base case
else:
return n * factorial(n - 1) # Recursive call
# Main function
def main():
num = int(input("Enter a positive integer: "))
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
result = factorial(num)
print(f"Factorial of {num} is {result}")
# Function call
main()
OUTPUT:
Enter a positive integer: 5
Factorial of 5 is 120
RESULT:
The program was executed successfully and it demonstrated the use
of user-defined and recursion in python.
5. Program using Strings.
AIM:
To Demonstrate the python program using string creation,
slicing, string methods and formatting
ALGORITHM:
Step 1: Start the program
Step 2: To read a string from the user using input ( )
Step 3: To show the length of the string using len ( )
Step 4: To perform the slicing operation given the substring
Step 5: To use common string methods like upper( ),lower ( ),tittle ( )
Step 6: Format and print the transformed strings
Step 7: Stop the program
Programm
def main():
name=input("Enter your name:")
city=input("Enter your city:")
message="Hello,"+ name +"!Welcome from"+ city+"."
length=len(message)
first_five=message[:5]
last_five=message[-5:]
upper_case=[Link]()
lower_case=[Link]()
title_case=[Link]()
print("\n.....String Operations.....")
print("original message:",message)
print("Length of message:",length)
print("First 5 characters:",first_five)
print("Last 5 characters:",last_five)
print("uppercase:",upper_case)
print("lowercase:",lower_case)
print("Titlecase:",title_case)
if__name__="__main__";
main()
OUTPUT:
Enter your name: shree
Enter your city: perambalur
.....String Operations.....
original message: Hello,shree!Welcome from perambalur.
Length of message: 35
First 5 characters: Hello
Last 5 characters: alur.
uppercase: HELLO,SHREE!WELCOME FROM PERAMBALUR.
lowercase: hello,shree!welcome from perambalur.
Titlecase: Hello,Shree!Welcome From perambalur.
RESULT:
The program was executed successfully and it demonstrated string
creation, slicing and string methods in python.
6. Program using Modules.
AIM
To demonstrate the use of built-in modules and user-defined modules in python.
ALGORITHM:
Step 1: Start the program
Step 2: To import the built-in modules like math, random, pi
etc.. Step 3: To use functions or constants from those modules
(eg.
[Link]() )
Step 4: Import the user-defined module
Step 5: To call the functions from the
module Step 6: Display the output using the
print ( ) Step 7:Stop the program
Programm
import math
def main():
number=16
square_root=[Link](number)
print(f"Square root of {number}is:{square_root}")
fact=[Link](5)
print(f"Factorial of 5 is:{fact}")
area=[Link]*(5**2)
print(f"Area of circle with radius 5 is:{area:.2f}")
main()
OUTPUT:
Square root of 16is:4.0
Factorial of 5 is:120
f circle with radius 5 is:78.54
RESULT:
The program was executed successful and it demonstrated the built-in modules in
python
7. Program using Lists and Tuples and Dictionaries
AIM
To write a python program to demonstrate the creation and append operation on List,
Tuple and Dictionary.
ALGORITHM:
Step 1: Start the program
Step 2: Create a list, a tuple and a dictionaries with example values
Step 3: Perform list operation append and slicing operation on the
given list
Step 4: Show tuple properties and access elements from the
tuples Step 5: Demonstrate dictionary operation to update a key
Step 6: print outputs after each operation to show
effect Step 7:Stop the program
def main():
fruits=["apple","banana","cherry"]
print("original list of fruits:",fruits)
[Link]("orange")
print("After Adding:",fruits)
print("first fruits:",fruits[0])
colors=("red","green","blue")
print("\nTuples of colors:",colors)
print("second color:",colors[1])
student={
"name":"Arun",
"age":20,
"course":"[Link] Computer Science"
print("\nDictionary of student:",student)
print("Student Name:",student["name"])
student["grade"]="A"
print("update student Dictionary:",student)
main()
OUTPUT:
original list of fruits: ['apple', 'banana', 'cherry']
After Adding: ['apple', 'banana', 'cherry', 'orange']
first fruits: apple
Tuples of colors: ('red', 'green', 'blue')
second color: green
Dictionary of student: {'name': 'Arun', 'age': 20, 'course': '[Link] Computer Science'}
Student Name: Arun
update student Dictionary: {'name': 'Arun', 'age': 20, 'course': '[Link] Computer Science',
'grade': 'A'}
RESULT:
The program was executed successfully and it demonstrated the
creation and append operation on list, Tuple and dictionary in
python.
8. Program for File Handling.
AIM
To demonstrate reading from and writing to text files
ALGORITHM:
Step 1: Start the program
Step 2: Open a file in write mode and to write a required data and
close automatically
Step 3: Re-open the file in read mode to read the contents
Step 4: Process or display the read text
Step 5: Open a file in append mode to add more data and ensure
writes are flushed/committed before closing
Step 6: Close the file
Step 7: Stop the
program
Programm
def main():
filename = "[Link]"
with open(filename, "w") as file:
[Link]("Hello, this is the first line.\n")
[Link]("Python file handling is simple!\n")
print("File created and written successfully.")
with open(filename, "r") as file:
print("\n--- File Content (Read Mode) ---")
content = [Link]()
print(content)
with open(filename, "a") as file:
[Link]("This line is added later.\n")
print("\nNew content appended to the file.")
with open(filename, "r") as file:
print("\n--- File Content (Line by Line) ---")
for line in file:
print([Link]())
if __name__ == "__main__":
main()
OUTPUT:
File created and written successfully.
--- File Content (Read Mode) ---
Hello, this is the first line.
Python file handling is simple!
New content appended to the file.
--- File Content (Line by Line) ---
Hello, this is the first line.
Python file handling is simple!
This line is added later.
RESULT:
The program was executed successfully and its demonstrated the use of reading from
and writing text files in python
9. Create a GUI program using PyGTK
AIM:
To Build a simple GUI window with widgets(label, buttons)
using tkinter
ALGORITHM:
Step 1: Start the program
Step 2: Import tkinter (import tkinter as tk or from tkinter
import) Step 3: Create a main window root=[Link]( ) and set
title/size
Step 4: Create widgets like labels, entry, button etc… and place
them using pack( ), grid( ) or place ( )
Step 5: Define callback functions that run when a button is
clicked Step 6: Attach callbacks with command=on buttons
Step 7: Start GUI event loop with [Link]( )
Step 8: Stop the program
Programm
import tkinter as tk
from tkinter import messagebox
def on_button_click():
[Link]("Hello", "Welcome to the GUI program!")
window = [Link]()
[Link]("Simple GUI Program")
label = [Link](window, text="Hello, this is a GUI program.")
[Link](pady=10)
button = [Link](window, text="Click Me", command=on_button_click)
[Link](pady=10)
[Link]()
OUTPUT:
RESULT:
The program was executed successfully and its demonstrated thecreation
of a simple GUI application using Tkinter in python.
10. Connect with MySQL and create address book.
AIM:
To write a python program to connect a MySQL database and
implement a simple address book with CRUD operations
ALGORITHM:
Step 1: Start the program
Step 2: Install & import connector
Step 3: Establish connection to provide host, user, password,
database Step 4: Create a table address_book (columns: id, name,
phone,
address) if it does not exist
Step 5: Provides functions for
Create: insert a new contact(INSERT)
Read: fetch contacts(SELECT)
Update: modify a contact(UPDATE WHERE id=)
Delete: remove a contact (DELETE WHERE id=)
Step 6: After each operation commit the transaction and show
confirmation
Step 7: Close cursor and connection
Step 8: Stop the program
Programm
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)
RESULT:
The program was executed and successfully and it demonstrated
how to connect python with MySQL and perform basic CRUD operation for
an address book.