0% found this document useful (0 votes)
2 views21 pages

Advance Python Lab Complete

The document outlines a series of experiments for an Advanced Python Programming course at Sagar Institute of Research and Technology, focusing on various programming concepts such as data types, client-server communication, web scraping, CGI scripting, and concurrent programming. Each experiment includes objectives, code implementations, and expected outputs to demonstrate the practical applications of Python in different contexts. The document serves as a comprehensive guide for students to understand and apply advanced Python programming techniques.
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)
2 views21 pages

Advance Python Lab Complete

The document outlines a series of experiments for an Advanced Python Programming course at Sagar Institute of Research and Technology, focusing on various programming concepts such as data types, client-server communication, web scraping, CGI scripting, and concurrent programming. Each experiment includes objectives, code implementations, and expected outputs to demonstrate the practical applications of Python in different contexts. The document serves as a comprehensive guide for students to understand and apply advanced Python programming techniques.
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

Sagar Institute of Research and Technology, Bhopal

Department of Cyber Security

Name of the faculty: Prof. Priyanka Soni Session (2024-25)

Subject: Advance Python Programming CY-406

Index

Date of
[Link]. List Of Experiments Remark
Experiment

To Write a program in python to demonstrate


1 different data types (int, float, str, bool) and
their operations.

2 To Create a simple TCP client that sends a


message to a server and receives a response.
3 To write a program to Use libraries like
BeautifulSoup to extract specific data (e.g.,
titles, links) from an HTML webpage..
4 To Create a simple CGI script that takes
user input and display it on a webpage.

5 To Develop a Python program to create a


simple TCP/UDP server that listens for
incoming connections and responds with a
message.
6 To demonstrate the use of concurrent
programming with threads in Python.

7 To understand and implement message passing


and data serialization using Python.

To create a simple distributed computing


8
application using the actor model
To explore different I/O handling models in
9
Python.

To understand and implement generators


10
and coroutines in Python for cooperative
multitasking.
Experiment01

Aim:-ToWrite a program in python to demonstrate different data types (int, float,


str, bool) and their operations

Objective: Demonstrate different data types: This includes integers (int), floats (float), strings
(str), and booleans (bool). The program shows how to assign values to variables of each data
type and how to print them. Illustrate basic operations on data types: It showcases arithmetic
operations like addition, multiplication, and division for integers and floats. Additionally, it
displays string concatenation and methods like converting to uppercase and finding length.
Introduce boolean logic: The program incorporates boolean variables and uses and, or, and not
operators to combine conditions and demonstrate how they evaluate to True or False.

CodeImplementation:

# Integer (int)
age = 30
print("Age (int):", age)

# Float (float)
pi = 3.14159
print("Pi (float):", pi)

# String (str)
name = "Alice"
print("Name (str):", name)

# Boolean (bool)
is_registered = True
print("Is registered (bool):", is_registered)

# Operations on integers
print("Age + 5:", age + 5)
print("Age * 2:", age * 2)

# Operations on floats (be mindful of rounding errors)


print("Pi / 2:", pi / 2)
print("Pi * Pi:", pi * pi)

# String operations (concatenation)


full_name = name + " Smith"
print("Full Name:", full_name)
# String methods
print("Name in uppercase:", [Link]())
print("Length of name:", len(name))

# Boolean logic (and, or, not)


is_adult = age >= 18
print("Is adult:", is_adult and is_registered) # True if both conditions are True
print("Not registered:", not is_registered)

CodeOutput:

Age (int): 30
Pi (float): 3.14159
Name (str): Alice
Is registered (bool): True
Age + 5: 35
Age * 2: 60
Pi / 2: 1.570795
Pi * Pi: 9.869587728099999
Full Name: Alice Smith
Name in uppercase: ALICE
Length of name: 5
Is adult: True
Not registered: False

The program Demonstrates:

 Assigning values to variables of different data types (int, float, str, bool).

 Printing the data type of each variable using the type() function (not shown in this code).

 Performing basic arithmetic operations on integers and floats.

 String concatenation to combine strings.

 Using string methods like upper() and len().

 Boolean logic operators (and, or, not) to combine condition


Experiment02

Aim:-ToCreate a simple TCP client that sends a message to a server and receives a
response

Objective: Understand client-server communication using sockets (TCP and UDP). Explore
libraries for web interaction (e.g., urllib).

CodeImplementation:

import socket

# Server IP address and port (same as client)


SERVER_ADDRESS = ("localhost", 12345)

# Create a TCP socket


server_socket = [Link](socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the address and port


server_socket.bind(SERVER_ADDRESS)

# Listen for incoming connections (maximum 1 connection queued)


server_socket.listen(1)

print("Server started listening on port:", SERVER_ADDRESS[1])

# Wait for a client connection


client_socket, client_address = server_socket.accept()

print("Client connected from:", client_address)

# Receive data from the client


received_data = client_socket.recv(1024).decode()

# Print the received data


print("Received from client:", received_data)

# Send a response (echo the received message)


client_socket.sendall(received_data.encode())

# Close the client socket


client_socket.close()

# Close the server socket


server_socket.close()
Server Output:
Server started listening on port: 12345
Client connected from: ('localhost', port_number) # port_number will be a specific number
assigned by the system.
Received from client: Hello from the client!
Clint Output:
Received from server: Hello from the client!

The Program Demonstrates:

 The server first prints a message indicating it's listening on port 12345.

 When the client connects, the server prints another message showing the client's IP address
and the port number it used for the connection.

 The server then receives the message sent by the client ("Hello from the client!"). Both the
server and client print the received data.

 Finally, the server echoes back the received message as a response, which is printed by the
client.
Experiment03

Aim:-To write a program to Use libraries like BeautifulSoup to extract


specific data (e.g., titles, links) from an HTML webpage.

Objective:Learn to process common data formats like HTML, XML, and [Link] using
the ElementTree library for XML parsing.

CodeImplementation:

import requests
from bs4 import BeautifulSoup

# Define the target URL


url = "[Link] # Replace with your desired URL

# Fetch the HTML content


response = [Link](url)

# Check for successful response


if response.status_code == 200:
# Parse the HTML content
soup = BeautifulSoup([Link], "[Link]")

# Extract titles
titles = []
for h tag in soup.find_all(["h1", "h2", "h3"]):
[Link](h_tag.[Link]()) # Extract text and remove whitespace

# Extract links
links = []
for a_tag in soup.find_all("a", href=True):
[Link](a_tag["href"])

# Print extracted data


print("Titles:")
for title in titles:
print(title)

print("\nLinks:")
for link in links:
print(link)
else:
print(f"Failed to retrieve webpage. Status code: {response.status_code}")
Output:

Titles:
Main Page
From Wikipedia, the free encyclopedia
Recently featured
Grant's Canal
Philadelphia Athletics 18, Cleveland Indians 17 (1932)
Fairfax Harrison
... (more titles)

Links:
/wiki/Grant's_Canal
/wiki/1932_World_Series
/wiki/Fairfax_Harrison
... (more links)

The Program Demonstrates:

This program demonstrates basic extraction. Real-world websites may have more complex
structures. You might need to adjust the selectors (e.g., tag names, attributes) based on the
specific webpage you're targeting. Be mindful of website [Link] to avoid excessive
scraping that can overload servers.
Experiment 04

Aim:- To Create a simple CGI script that takes user input and display it on a webpage.

Objective: Gain an introduction to web development concepts in Python (CGI, WSGI).

Code Implementation:

#!/usr/bin/env python

# Import libraries (depending on your web server setup)


import cgi

def main():
# Get form data
form = [Link]()
user_input = [Link]("user_input")

# Create HTML content


html_content = """
<html>
<head>
<title>User Input</title>
</head>
<body>
"""
if user_input:
# Display user input if available
html_content += f"<h1>You entered: {user_input}</h1>"
else:
# Display message if no input was provided
html_content += "<h1>No input received!</h1>"
html_content += """
</body>
</html>
"""

# Set content type header (important!)


print("Content-Type: text/html\n\n")

# Print the HTML content


print(html_content)

if __name__ == "__main__":
main()
Output:

The program Demonstrates:

1. User Input Handling:

 It utilizes the cgi module (depending on your web server setup) to access data submitted through an HTML
form.
 It retrieves the value of a specific form field named "user_input" using [Link]("user_input").

2. Dynamic HTML Generation:

 The script constructs the HTML content dynamically based on the user input.
 It incorporates the user input into the heading (<h1>You entered: {user_input}</h1>) using string formatting.

3. Web Server Interaction:

 The script is designed to be executed by a web server in response to a form submission.


 It sets the essential Content-Type header to text/html before sending the HTML content. This informs the
browser how to interpret the data.

4. Basic Error Handling (Improved Version):

 The improved version checks if the user_input has a value using an if statement.
 It displays a more informative message ("No input received!") if the user leaves the input field empty.

In essence, the script demonstrates how a CGI script can interact with user input from an HTML form, dynamically
generate HTML content, and communicate with a web server to display the results on a webpage.
Experiment 05

Aim:- Develop a Python program to create a simple TCP/UDP server that listens for
incoming connections and responds with a message.

Objective: Understand advanced network programming concepts like custom servers, concurrency,
and SSL.

Code Implementation:

import socket

# Server IP address (replace with your server's IP if needed)


SERVER_ADDRESS = ("localhost", 12345)

# Message to send to clients


message = "Hello from the TCP server!"

# Create a TCP socket


tcp_server = [Link](socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the address and port


tcp_server.bind(SERVER_ADDRESS)

# Listen for incoming connections (maximum 1 connection queued)


tcp_server.listen(1)

print("TCP server started listening on port:", SERVER_ADDRESS[1])

# Accept a connection and handle it in a loop


while True:
# Wait for a client connection
client_socket, client_address = tcp_server.accept()
print("TCP client connected from:", client_address)

# Send the message to the client


client_socket.sendall([Link]())

# Close the client socket (connection)


client_socket.close()

# Close the server socket (never reached in this example)


tcp_server.close()

UDP SERVER

import socket

# Server IP address (replace with your server's IP if needed)


SERVER_ADDRESS = ("localhost", 12346)

# Message to send to clients


message = "Hello from the UDP server!"

# Create a UDP socket


udp_server = [Link](socket.AF_INET, socket.SOCK_DGRAM)

# Bind the socket to the address and port


udp_server.bind(SERVER_ADDRESS)

print("UDP server started listening on port:", SERVER_ADDRESS[1])


# Listen for incoming data (UDP doesn't establish connections)
while True:
# Receive data (and client address) from the client
received_data, client_address = udp_server.recvfrom(1024)
print("UDP data received from:", client_address)

# Send the message to the client (using client address for UDP)
udp_server.sendto([Link](), client_address)

# Close the server socket (never reached in this example)


udp_server.close()

Output:

TCP Server Output:

 Server startup: When you run python tcp_server.py, you'll see a message indicating the
server has started listening on the specified port (e.g., "TCP server started listening on port:
12345").

 Client connection: Each time a client connects to the server (using a TCP client program),
you'll see a message indicating a client connection from that client's IP address and port (e.g.,
"TCP client connected from: ('localhost', port_number)").

UDP Server Output:

 Server startup: Similar to TCP, running python udp_server.py will print a message
indicating the server is listening on the specified port (e.g., "UDP server started listening on
port: 12346").

 Data received: The server will print a message every time it receives data from a client,
even if the data is empty (e.g., "UDP data received from: ('localhost', port_number)"). This is
because UDP is connectionless, and the server receives data packets without establishing a
connection.
Experiment 06

Aim:- To demonstrate the use of concurrent programming with threads in Python.

Objective: Gain an understanding of creating and managing threads, synchronizing threads, and
utilizing the threading library in Python.

Code Implementation:

import threading
import time

def print_numbers():
for i in range(10):
print(i)
[Link](1)

def print_letters():
for letter in 'abcdefghij':
print(letter)
[Link](1)

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

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

# Wait for threads to complete


[Link]()
[Link]()

print("Threads have finished execution.")

Output:

0
a
1
b
2
c
3
d
4
e
5
f
6
g
7
h
8
i
9
j
Threads have finished execution.

The program Demonstrates:

 Creating Threads:
 How to create and start multiple threads.
 How to wait for threads to complete using join().
Experiment 07

Aim:- To understand and implement message passing and data serialization using Python.

Objective: The objective of this experiment is to introduce students to the concepts of inter-process
communication (IPC) using message passing and to demonstrate how to serialize and deserialize
data using the pickle module in Python.

Code Implementation:

import multiprocessing

def sender(queue):
messages = ["Hello", "World", "Message Passing", "in", "Python"]
for message in messages:
[Link](message)
print(f"Sent: {message}")

def receiver(queue):
while True:
message = [Link]()
if message is None:
break
print(f"Received: {message}")

if __name__ == "__main__":
queue = [Link]()
process1 = [Link](target=sender, args=(queue,))
process2 = [Link](target=receiver, args=(queue,))

[Link]()
[Link]()
[Link]()
[Link](None) # Signal the receiver to stop
[Link]()

Output:

Sent: Hello
Sent: World
Sent: Message Passing
Sent: in
Sent: Python
Received: Hello
Received: World
Received: Message Passing
Received: in
Received: Python
Experiment 08

Aim:- To create a simple distributed computing application using the actor model

Objective: Understand the basics of distributed computing and implement an actor-based system
using Python.

Code Implementation:
import time
import random
from multiprocessing import Process, Pipe

# Define the Actor class


class Actor:
def __init__(self, name, conn):
[Link] = name
[Link] = conn

def send(self, msg):


print(f"{[Link]} sending message: {msg}")
[Link](msg)

def receive(self):
while True:
msg = [Link]()
print(f"{[Link]} received message: {msg}")
if msg == "stop":
break

def actor_process(name, conn):


actor = Actor(name, conn)
[Link]()

if __name__ == "__main__":
# Create two pairs of pipes for bidirectional communication
parent_conn1, child_conn1 = Pipe()
parent_conn2, child_conn2 = Pipe()

# Create two actor processes


actor1 = Process(target=actor_process, args=("Actor1", child_conn1))
actor2 = Process(target=actor_process, args=("Actor2", child_conn2))

# Start the actor processes


[Link]()
[Link]()

# Parent process sending messages to actors


parent_conn1.send("Hello from main to Actor1")
parent_conn2.send("Hello from main to Actor2")

[Link](1)

# Actor1 sending message to Actor2 through the main process


parent_conn1.send("Hello Actor2 from Actor1")
msg = parent_conn1.recv()
parent_conn2.send(msg)

[Link](1)

# Stop the actors


parent_conn1.send("stop")
parent_conn2.send("stop")
# Wait for actors to finish
[Link]()
[Link]()

Output:

Actor1 received message: Hello from main to Actor1


Actor2 received message: Hello from main to Actor2
Actor1 sending message: Hello Actor2 from Actor1
Actor2 received message: Hello Actor2 from Actor1
Actor1 received message: stop
Actor2 received message: stop

The program Demonstrates:

Message Passing:
 Actors send and receive messages using pipes, simulating inter-process communication.
Distributed Computing:
 The actors run in separate processes, showcasing basic distributed computing concepts.
Actor Model:
 The program implements a simple actor model where actors communicate by sending and
receiving messages.
Experiment 09

Aim:- To explore different I/O handling models in Python.

Objective: The objective of this experiment is to understand various I/O models and how they can
be implemented in Python to handle input/output operations efficiently.

Code Implementation:
# Blocking I/O example
import socket

def blocking_io_example():
with [Link](socket.AF_INET, socket.SOCK_STREAM) as s:
[Link](('[Link]', 80))
[Link](b'GET / HTTP/1.1\r\nHost: [Link]\r\n\r\n')
data = [Link](1024)
print('Received', repr(data))

if __name__ == "__main__":
blocking_io_example()

Output:

The blocking I/O example will block the program until data is received.

The program Demonstrates:

In this experiment, we have explored different I/O handling models in Python. We implemented
blocking I/O.
Experiment 10

Aim:- To understand and implement generators and coroutines in Python for cooperative
multitasking.

Objective: The objective of this experiment is to learn how to use generators and coroutines in
Python to implement cooperative multitasking and efficient data processing.

Code Implementation:

# Generator for processing large data


def large_data_generator(n):
for i in range(n):
yield i * 2

gen = large_data_generator(1000000)
for value in gen:
if value % 100000 == 0:
print(value)

Output:

The generator examples will produce sequences of values on demand without holding the entire
sequence in memory.

The program Demonstrates:


 In this experiment, we have explored the concepts of generators and coroutines in Python

You might also like