Python Programming Laboratory Manual - 20241011 - 135938 - 0000
Python Programming Laboratory Manual - 20241011 - 135938 - 0000
NOTE 💥
IF ANY ERROR IN PROGRAM MEAN CHANGE THE LITTER CAPITAL TO
SMALL
1 → Write a program to create, concatenate and print a string and accessing sub-string
from given string.
Aim:
To create, concatenate and print a string and accessing sub-string from given string
Algorithm:
3. Print str3.
Program:
Str1 = “Hello”
Str2 = “World”
Sub_str = full_str[6:]
Print(“Sub-String: “, sub_str)
Output:
Sub-String: World
RESULT:
The program creates and concatenates two strings, then prints the result and a substring
from the concatenated string.
2 → Write a python program to create append and remove lists in python
Aim:
Algorithm:
Program:
my_list = []
my_list.append(1)
my_list.append(2)
my_list.append(3)
my_list.append(4)
my_list.append(5)
print(my_list)
my_list.append(6)
print(my_list)
my_list.remove(4)
print(my_list)
my_list.pop()
print(my_list)
Output:
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 5, 6]
[1, 2, 3, 5]
RESULT: The program creates a list, appends items, removes a specific item, and pops the
last item, displaying the list at each step.
3 → Write a program to demonstrate working tuples in python
Aim:
Algorithm:
3. Print `my_list`.
4. Append another element to `my_list`.
Program:
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple)
print(my_tuple[0])
print(my_tuple[-1])
print(my_tuple[1:4])
print(my_tuple * 2)
print(4 in my_tuple)
print(len(my_tuple))
print(list(my_tuple))
Output:
(1, 2, 3, 4, 5)
(2, 3, 4)
(1, 2, 3, 4, 5, 6, 7, 8)
(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
True
[1, 2, 3, 4, 5]
RESULT:
The program demonstrates tuple creation, element access, concatenation, immutability,
and modifying a tuple by converting it to a list.
4 → Write a program to demonstrate working with dictionaries in python
Aim:
Algorithm:
3. Print `my_dict`.
4. Access and print a value by its key.
Program;
print(my_dict)
print(my_dict[“name”])
my_dict[“age”] = 31
print(my_dict)
my_dict[“country”] = “USA”
print(my_dict)
del my_dict[“age”]
print(my_dict)
print(“name” in my_dict)
Output:
John
True
RESULT:
**
***
****
*****
****
***
**
Aim:
To create a python program to construct the following pattern using nested for loop
Algorithm:
Program:
n=5
for i in range(n):
print('* ' * (i + 1))
Output:
**
***
****
*****
****
***
**
RESULT:
The program prints a pyramid pattern of stars, increasing and then decreasing in size.
6 → Write a python program to find factorial of a number using recursion
Aim:
Algorithm:
Program:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n – 1)
Enter a number: 5
RESULT:
The program recursively calculates and prints the factorial of a given number.
7 → Install package requests, flasks and explore using (pip)
Aim:
Algorithm:
Program;
pydoc requests
pydoc flask
Output:
---------- -------
Flask 2.2.2
Requests 2.28.2
RESULT:
The `requests` and `Flask` packages are installed using `pip`, and examples are shown
for making HTTP requests and creating a simple Flask web app.
8 → Elliptical orbits in pygame
Aim:
Algorithm:
5. Update planet velocity and position using gravity and time step
Program:
import pygame
import math
import sys
pygame.init()
screen=pygame.display.set_mode((600,300))
pygame.display.set_caption(“Elliptical orbit”)
clock=pygame.time.Clock()
while(True):
if event.type==pygame.QUIT:
sys.exit()
xRadius=250
yRadius=100
x1=int(math.cos(degree*2*math.pi/360)*xRadius)+300
y1=int(math.cos(degree*2*math.pi/360)*yRadius)+150
screen.fill((0,0,0))
pygame.draw.circle(screen,(0,255,0),[300,150],35)
pygame.draw.ellipse(screen,(255,255,255),[50,50,500,200],1)
pygame.draw.circle(screen,(0,0,255),[x1,y1],15)
pygame.display.flip()
clock.tick(10)
Output:
RESULT:
The program simulates an elliptical orbit using Pygame, with a planet moving around a
stationary sun.
9 → Stimulate bouncing ball using pygame
Aim:
Create a simulation of a bouncing ball using Pygame, showcasing a ball bouncing off the
edges of the screen with realistic physics.
Algorithm:
8. Update display
Note: This is a simplified outline and may require additional steps for a complete
simulation.
Program:
import pygame
pygame.init()
width =700
height =900
screen_res =(width,height)
pygame.display.set_caption("Bouncing game")
screen = pygame.display.set_mode(screen_res)
pink =(255,0,0)
black =(0,0,0)
ball_obj =pygame.draw.circle(surface=screen,color=pink,center=[100,100],radius=40)
speed =[3,3]
while True:
if event.type ==pygame.QUIT:
exit()
screen.fill(black)
ball_obj =ball_obj.move(speed)
if ball_obj.left<=0 or ball_obj.right>=width:
speed[0] = -speed[0]
if ball_obj.top<=0 or ball_obj.bottom>=height:
speed[1] = -speed[1]
pygame.draw.circle(surface=screen,color=pink,center=ball_obj.center,radius=40)
pygame.display.flip()
Output:
RESULT:
The program simulates a bouncing ball that moves around the screen and reverses
direction upon hitting the window edges.
10(15) → Write a python program to implement the following figure using turtle
Aim:
Algorith:
Program:
a)
Import turtle
T=turtle.Turtle()
t.speed(10)
t.pensize(5)
colors=[‘red’,’blue’,’green’]
for I in range(12):
t.color(colors[i%3])
t.circle(100)
t.right(60)
turtle.done()
OUTPUT:
b)
Import turtle
def draw_square(some_turtle):
some_turtle.forward(300)
some_turtle.right(90)
def draw_art():
window= turtle.Screen()
window.bgcolor(“white”)
brad=turtle.Turtle()
brad.shape(“turtle”)
brad.color(“black”)
brad.speed(60)
brad.pensize(5)
for I in range(1,37):
draw_square(brad)
brad.right(10)
angie=turtle.Screen()
angie.shape(“turtle”)
angie.color(“black”)
angie.speed(60)
angie.pensize(5)
size=1
while (Ture):
angie.forward(size)
angie.right(91)
size=size + 1
window.exitonclick()
draw_art()
Output:
RESULT:
The program uses Turtle graphics to draw a golden star on a light blue background.
11 (10). Write a python program to find the sub-string within a string using re module
Aim:
Algorithm:
4. If found:
- Print occurrences.
- Print positions.
5. If not found:
Program:
str=”welcome to the python world”
sub_str=”python”
print(str.find(sub_str))#11
if(str.find(sub_str)== -1):
print(“not found”)
else:
print(“found”)
Output:
11
Found
RESULT:
The program finds and prints all 4-letter words in a given string using the `re` module.
12(11) → Create a class ATM and define ATM operations to create account, deposit,
check balance, withdraw and delete account. Use constructor to initialize members.
Aim:
Algorithm:
1. Start
3. Define create_account():
4. Define deposit(amount):
a. If active:
i. If amount > 0:
ii. Else:
b. Else:
5. Define check_balance():
a. If active:
b. Else:
a. If active:
iii. Else:
b. Else:
7. Define delete_account():
a. If active:
b. Else:
8. Example usage:
9. End
Program:
Class ATM:
Def __init__(self):
Self.accounts = {}
If account_number in self.accounts:
Else:
If account_number in self.accounts:
Self.accounts[account_number][1] += amount
Else:
If account_number in self.accounts:
Else:
Print(“Account not found.”)
If account_number in self.accounts:
Self.accounts[account_number][1] -= amount
Else:
Print(“Insufficient balance.”)
Else:
If account_number in self.accounts:
Del self.accounts[account_number]
Else:
# Example usage:
Atm = ATM()
# Create accounts
Atm.create_account(1002, “Bob”)
# Deposit money
Atm.deposit(1001, 200)
# Check balance
Atm.check_balance(1001)
# Withdraw money
Atm.withdraw(1001, 100)
# Delete account
Atm.delete_account(1002)
Atm.check_balance(1002)
Output:
Balance for account 1001: 700 Withdrew 100. New balance: 600 Account 1002 deleted.
Result:
The ATM program successfully created an account, performed deposits and withdrawals,
checked the balance, and handled account deletion, displaying appropriate messages for
each operation.
13(16) →. Perform port scanning function for your system using Python
Aim:
To develop a Python program that performs port scanning to identify open ports on a target
system for security assessment and service discovery.
Algorithm:
1. Start
4. Initialize open_ports = []
5. For port in range(start_port, end_port + 1):
d. If result == 0 then:
e. Else:
7. End
Program:
Import socket
open_ports.append(port)
else:
return open_ports
# Example usage
If __name__ == “__main__”:
Start_port = 1
End_port = 1024
Print(f”Scanning ports on {target_ip} from {start_port} to {end_port}…”)
Output:
Port 22 is open
Port 80 is open
Result:
The port scanning program successfully identified open ports on the target system,
indicating that ports 22, 80, and 443 were open, while others in the specified range were
closed.
14(17) → Perform network scanning using python
Aim:
To develop a Python program that performs network scanning to identify active hosts on a
specified subnet using the Scapy library.
Algorithm:
1. Start
3. Define scan_network(ip_range):
5. Initialize active_hosts = []
7. Return active_hosts
8. End
Program:
Def scan_network(ip_range):
Arp_request = ARP(pdst=ip_range)
Ether = Ether(dst=”ff:ff:ff:ff:ff:ff”)
# Combine both
Active_hosts = []
Return active_hosts
# Example usage
If __name__ == “__main__”:
Active_hosts = scan_network(target_ip_range)
# Print results
Print(“Active hosts:”)
Outpu:
Active hosts:
Result:
The network scanning program successfully identified active hosts on the specified subnet,
displaying their IP and MAC addresses.
15(14) → Write a python program to perform various database operations (create,
insert, delete, update)
Aim:
The aim of the program is to demonstrate basic database operations (create, insert,
update, delete) using SQLite in Python.
Algorithm:
1. Start
2. INPUT num1
4. INPUT num2
5. IF operator = +
6. ELSE IF operator = -
7. ELSE IF operator = *
8. ELSE IF operator = /
9. DISPLAY result
10. END
Program:
Import sqlite3
Conn = sqlite3.connect(‘example.db’)
Cursor = conn.cursor()
Def create_table():
Cursor.execute(‘’’
‘’’)
Print(“Table created successfully.”)
Cursor.execute(‘’’
INSERT INTO users (name, age) VALUES (?, ?)
Conn.commit()
Print(f”Inserted user: {name}, Age: {age}”)
Cursor.execute(‘’’
Conn.commit()
Cursor.execute(‘’’
‘’’, (user_id,))
Conn.commit()
Users = cursor.fetchall()
Print(“User Records:”)
Print(user)
# Main operations
Insert_user(“Alice”, 30)
Insert_user(“Bob”, 25)
# Display users
Display_users()
# Update a user
Display_users()
# Delete a user
Delete_user(2)
Display_users()
Conn.close()
Output:
User Records:
User Records:
User Records:
Result:
Aim:
To create a GUI-based calculator using Tkinter that performs basic arithmetic operations
like addition, subtraction, multiplication, and division.
Algorithm:
1. INITIALIZATION
- Expression = “”
2. BUTTON CLICK
3. EVALUATE EXPRESSION
- Parse Expression
- RETURN Result
4. DISPLAY RESULT
END
Program:
import tkinter as tk
def update_display(value):
current_text = display_var.get()
if current_text == "0":
display_var.set(value)
else:
display_var.set(current_text + value)
def clear_display():
display_var.set("0")
def calculate_result():
try:
result = eval(display_var.get())
display_var.set(result)
except Exception:
display_var.set("Error")
parent = tk.Tk()
parent.title("Calculator")
display_var = tk.StringVar()
display_var.set("0")
display_label = tk.Label(parent, textvariable=display_var, font=("Arial", 24), bg="lightgray",
anchor="e")
display_label.grid(row=0, column=0, columnspan=4)
buttons = [
button.grid(row=row, column=col)
parent.mainloop()
Output:
Result:
Aim:
To a python program to read the file contents and print each word of a file in reverse order
Algorithm:
1. Open file.
2. Read contents.
Operations:
1. Search
1. Input string.
2. Check existence.
3. Print result.
2. Word Count
1. Split contents.
2. Count words.
3. Print count.
3. Line Count
1. Split contents.
2. Count lines.
3. Print count.
4. Find Line
2. Check existence.
3. Print line.
5. Replace String
2. Replace string.
3. Print updated.
Program:
Words=str.split(“ “)
Print (words)
Words =Words[-1::-1]
Print(words)
Str1=’ ‘.join(words)
Print(str1)
Output:
[‘welcome’,’to’,’the’, ‘python’,’world’]
RESULT:
The program reads the file contents and prints each word in reverse order.