0% found this document useful (0 votes)
15 views

Python Programming Laboratory Manual - 20241011 - 135938 - 0000

Uploaded by

san007msd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Python Programming Laboratory Manual - 20241011 - 135938 - 0000

Uploaded by

san007msd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

DEPARTMENT OF CYBERSECURITY

PYTHON PROGRAMMING LABORATOR

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:

1. Create two strings, str1 and str2.

2. Concatenate str1 and str2 with a space in between to form str3.

3. Print str3.

4. Access and print the sub-string from index 0 to 5 of str3.

5. Access and print the sub-string from index 7 to 12 of str3.

6. Access and print the character at index 0 of str3.

7. Access and print the character at the last index of str3.

Program:

Str1 = “Hello”

Str2 = “World”

Full_str = str1 + “ “ + str2

Print(“Concatenated String: “, full_str)

Sub_str = full_str[6:]

Print(“Sub-String: “, sub_str)
Output:

Concatenated String: Hello World

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:

To create append and remove lists in python

Algorithm:

1. Create an empty list `my_list`.

2. Append elements `1`, `2`, `3`, `4`, and `5` to `my_list`.

3. Print the updated `my_list`.

4. Append element `6` to `my_list`.

5. Print the updated `my_list`.

6. Remove element `4` from `my_list`.

7. Print the updated `my_list`.

8. Remove the last element from `my_list`.

9. Print the updated `my_list`.

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:

To create a program to demonstrate working tuples in python

Algorithm:

1. Initialize an empty list `my_list`.

2. Append elements to `my_list`.

3. Print `my_list`.
4. Append another element to `my_list`.

5. Print `my_list` again.

6. Remove a specific element from `my_list`.

7. Print `my_list` after removal.

8. Remove the last element from `my_list`.

9. Print the final state of `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 + (6, 7, 8))

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:

To create a program to demonstrate working with dictionaries in python

Algorithm:

1. Create a dictionary `my_dict`.

2. Add key-value pairs to `my_dict`.

3. Print `my_dict`.
4. Access and print a value by its key.

5. Update a value in `my_dict`.

6. Remove a key-value pair from `my_dict`.

7. Check if a key exists in `my_dict`.

8. Print `my_dict` again.

Program;

my_dict = {“name”: “John”, “age”: 30}

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:

{‘name’: ‘John’, ‘age’: 30}

John

{‘name’: ‘John’, ‘age’: 31}


{‘name’: ‘John’, ‘age’: 31, ‘country’: ‘USA’}

{‘name’: ‘John’, ‘country’: ‘USA’}

True

RESULT:

The program demonstrates creating a dictionary, accessing, adding, updating, removing


key-value pairs, and checking for key existence.
5 → Write a python program to construct the following pattern using nested for loop

**

***

****

*****

****

***

**

Aim:

To create a python program to construct the following pattern using nested for loop

Algorithm:

1. Outer loop from 1 to 5

2. Inner loop from 1 to outer loop variable

3. Print '*' times inner loop variable

4. Outer loop from 4 to 1

5. Inner loop from 1 to outer loop variable

6. Print '*' times inner loop variable

Program:

n=5
for i in range(n):
print('* ' * (i + 1))

for i in range(n - 1, -1, -1):

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:

To create a python program to find factorial of a number using recursion

Algorithm:

1. Define a function `factorial(n)` that takes an integer `n` as input.

2. If `n` is 0 or 1, return 1 (base case).


3. Otherwise, return `n` multiplied by the result of `factorial(n-1)` (recursive call).

4. Call the `factorial` function with the desired number as argument.

Program:

def factorial(n):

if n == 0 or n == 1:

return 1

else:

return n * factorial(n – 1)

num = int(input(“Enter a number: “))

print(“Factorial of”, num, “is:”, factorial(num))


Output:

Enter a number: 5

Factorial of 5 is: 120

RESULT:

The program recursively calculates and prints the factorial of a given number.
7 → Install package requests, flasks and explore using (pip)

Aim:

Install and explore requests and Flask packages using pip

Algorithm:

1. Open terminal/command prompt

2. Install requests: `pip install requests`

3. Install Flask: `pip install flask`

4. Verify installation: `pip list requests flask`

5. Explore requests: `pydoc requests` or `help(requests)`

6. Explore Flask: `pydoc flask` or `help(Flask)`

Program;

pip install requests flask


pip list requests flask

pydoc requests
pydoc flask

Output:

Successfully installed flask-2.2.2 requests-2.28.2


Package Version

---------- -------

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:

Create a simulation of elliptical orbits using Pygame, showcasing planets or objects


moving in elliptical paths around a central body.

Algorithm:

1. Initialize Pygame and set up display

2. Define planet properties (position, velocity, mass, radius)

3. Define central body properties (position, mass)

4. Calculate gravitational force between planet and central body

5. Update planet velocity and position using gravity and time step

6. Draw planet and central body on screen

7. Repeat steps 4-6 for each planet

8. Handle user input and update display

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):

for event in pygame.event.get():

if event.type==pygame.QUIT:

sys.exit()

xRadius=250

yRadius=100

for degree in range(0,360,10):

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:

1. Initialize Pygame and set up display

2. Define ball properties (position, velocity, radius, color)


3. Set up game loop

4. Move ball by updating position with velocity


5. Check for collision with screen edges

6. Reverse velocity component on collision (bounce)

7. Draw ball on screen

8. Update display

9. Repeat steps 4-8

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:

for event in pygame.event.get():

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:

Draw a colorful spiral pattern using Python’s turtle module.

Algorith:

1. Import turtle module

2. Set up screen with black background

3. Create turtle object for drawing

4. Set drawing speed to fastest

5. Define list of colors for spiral pattern

6. Loop through 360 iterations:

a. Set pen color to current color in list (cycle through list)

b. Move forward by current iteration number (increases spiral size)

c. Turn left by 1 degree (creates spiral shape)

7. Keep window open until closed by user


Note: This algorithm uses a simple loop to create the spiral pattern, increasing the
distance moved forward and changing the color for each iteration.

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):

for I in range (1,5):

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:

To find the sub-string within a string using re module

Algorithm:

Substring Search Algorithm

1. Input main string and substring.

2. Compile substring into pattern.

3. Search pattern in main string.

4. If found:

- Print success message.

- Print occurrences.

- Print positions.

5. If not found:

- Print failure message.

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:

To create account, deposit, check balance, withdraw and delete account

Algorithm:
1. Start

2. Define class ATM:

a. Initialize account_number, account_holder, balance, active

3. Define create_account():

a. Print account creation confirmation

4. Define deposit(amount):

a. If active:

i. If amount > 0:

- Add amount to balance

- Print new balance

ii. Else:

- Print “Deposit amount must be positive.”

b. Else:

- Print “Account is inactive. Cannot deposit.”

5. Define check_balance():

a. If active:

- Print current balance

b. Else:

- Print “Account is inactive. Cannot check balance.”


6. Define withdraw(amount):

a. If active:

i. If amount > 0 and amount <= balance:

- Subtract amount from balance

- Print new balance

ii. If amount > balance:

- Print “Insufficient funds.”

iii. Else:

- Print “Withdrawal amount must be positive.”

b. Else:

- Print “Account is inactive. Cannot withdraw.”

7. Define delete_account():

a. If active:

- Set active to False

- Print account deletion confirmation

b. Else:

- Print “Account is already inactive.”

8. Example usage:

a. Create ATM instance

b. Call create_account(), check_balance(), deposit(), withdraw(), delete_account()

c. Call check_balance() after deletion

9. End
Program:

Class ATM:

Def __init__(self):

# Dictionary to store account information (account_number: [name, balance])

Self.accounts = {}

Def create_account(self, account_number, name, initial_deposit=0):

If account_number in self.accounts:

Print(“Account already exists.”)

Else:

Self.accounts[account_number] = [name, initial_deposit]


Print(f”Account created for {name} with initial deposit of {initial_deposit}.”)

Def deposit(self, account_number, amount):

If account_number in self.accounts:

Self.accounts[account_number][1] += amount

Print(f”Deposited {amount}. New balance: {self.accounts[account_number][1]}”)

Else:

Print(“Account not found.”)

Def check_balance(self, account_number):

If account_number in self.accounts:

Print(f”Balance for account {account_number}:


{self.accounts[account_number][1]}”)

Else:
Print(“Account not found.”)

Def withdraw(self, account_number, amount):

If account_number in self.accounts:

If self.accounts[account_number][1] >= amount:

Self.accounts[account_number][1] -= amount

Print(f”Withdrew {amount}. New balance: {self.accounts[account_number][1]}”)

Else:

Print(“Insufficient balance.”)

Else:

Print(“Account not found.”)

Def delete_account(self, account_number):

If account_number in self.accounts:

Del self.accounts[account_number]

Print(f”Account {account_number} deleted.”)

Else:

Print(“Account not found.”)

# Example usage:

Atm = ATM()

# Create accounts

Atm.create_account(1001, “Alice”, 500)

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)

# Attempt to access a deleted or non-existing account

Atm.check_balance(1002)
Output:

Account created for Alice with initial deposit of 500.

Account created for Bob with initial deposit of 0.

Deposited 200. New balance: 700

Balance for account 1001: 700 Withdrew 100. New balance: 600 Account 1002 deleted.

Account not found.

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

2. Import socket module


3. Define scan_ports(target, start_port, end_port)

4. Initialize open_ports = []
5. For port in range(start_port, end_port + 1):

a. Create socket object


b. Set timeout to 1 second

c. result = socket.connect_ex((target, port))

d. If result == 0 then:

i. Print “Port [port] is open”

ii. Append port to open_ports

e. Else:

i. Print “Port [port] is closed”

6. Print “Open ports: [open_ports]”

7. End
Program:

Import socket

Def scan_ports(target, start_port, end_port):

Open_ports = [] # List to store open ports

# Loop through the specified range of ports

For port in range(start_port, end_port + 1):

With socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:

# Set a timeout for the connection attempt

s.settimeout(1) # 1 second timeout

result = s.connect_ex((target, port)) # Check the port

if result == 0: # Port is open

open_ports.append(port)

print(f”Port {port} is open”)

else:

print(f”Port {port} is closed”)

return open_ports

# Example usage
If __name__ == “__main__”:

Target_ip = “127.0.0.1” # Localhost

Start_port = 1

End_port = 1024
Print(f”Scanning ports on {target_ip} from {start_port} to {end_port}…”)

Open_ports = scan_ports(target_ip, start_port, end_port)

Print(“\nOpen ports:”, open_ports)

Output:

Scanning ports on 127.0.0.1 from 1 to 1024…

Port 22 is open

Port 80 is open

Port 443 is open

Port 1024 is closed

Open ports: [22, 80, 443, …]

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

2. Import necessary functions from scapy

3. Define scan_network(ip_range):

a. Create ARP request for ip_range


b. Create Ethernet frame to broadcast request

c. Combine ARP request and Ethernet frame into packet

4. Send packet and receive responses using srp()

5. Initialize active_hosts = []

6. For each response in received:

a. Extract IP and MAC address

b. Append IP and MAC to active_hosts

7. Return active_hosts

8. End
Program:

From scapy.all import ARP, Ether, srp

Def scan_network(ip_range):

# Create an ARP request

Arp_request = ARP(pdst=ip_range)

# Create an Ethernet frame

Ether = Ether(dst=”ff:ff:ff:ff:ff:ff”)
# Combine both

Packet = ether / arp_request

# Send the packet and receive the response


Result = srp(packet, timeout=2, verbose=False)[0]

# List to hold active hosts

Active_hosts = []

# Process the response

For sent, received in result:

Active_hosts.append({‘ip’: received.psrc, ‘mac’: received.hwsrc})

Return active_hosts

# Example usage
If __name__ == “__main__”:

Target_ip_range = “192.168.1.0/24” # Adjust this to your network


Print(f”Scanning network: {target_ip_range}…”)

Active_hosts = scan_network(target_ip_range)

# Print results

Print(“Active hosts:”)

For host in active_hosts:

Print(f”IP: {host[‘ip’]}, MAC: {host[‘mac’]}”)

Outpu:

Scanning network: 192.168.1.0/24…

Active hosts:

IP: 192.168.1.1, MAC: 00:11:22:33:44:55

IP: 192.168.1.5, MAC: 66:77:88:99:AA:BB

IP: 192.168.1.10, MAC: CC:DD:EE:FF:00:11

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

3. INPUT operator (+, -, *, /)

4. INPUT num2
5. IF operator = +

THEN result = num1 + num2

6. ELSE IF operator = -

THEN result = num1 – num2

7. ELSE IF operator = *

THEN result = num1 * num2

8. ELSE IF operator = /

THEN result = num1 / num2

9. DISPLAY result
10. END
Program:

Import sqlite3

# Connect to SQLite database (or create it if it doesn’t exist)

Conn = sqlite3.connect(‘example.db’)

# Create a cursor object

Cursor = conn.cursor()

# Function to create a table

Def create_table():

Cursor.execute(‘’’

CREATE TABLE IF NOT EXISTS users (

Id INTEGER PRIMARY KEY AUTOINCREMENT,

Name TEXT NOT NULL,

Age INTEGER NOT NULL

‘’’)
Print(“Table created successfully.”)

# Function to insert a new user

Def insert_user(name, age):

Cursor.execute(‘’’
INSERT INTO users (name, age) VALUES (?, ?)

‘’’, (name, age))

Conn.commit()
Print(f”Inserted user: {name}, Age: {age}”)

# Function to update a user’s details

Def update_user(user_id, name, age):

Cursor.execute(‘’’

UPDATE users SET name = ?, age = ? WHERE id = ?

‘’’, (name, age, user_id))

Conn.commit()

Print(f”Updated user with ID: {user_id}”)

# Function to delete a user


Def delete_user(user_id):

Cursor.execute(‘’’

DELETE FROM users WHERE id = ?

‘’’, (user_id,))

Conn.commit()

Print(f”Deleted user with ID: {user_id}”)

# Function to display all users


Def display_users():

Cursor.execute(‘SELECT * FROM users’)

Users = cursor.fetchall()

Print(“User Records:”)

For user in users:

Print(user)
# Main operations

Create_table() # Create the table

# Insert sample users

Insert_user(“Alice”, 30)

Insert_user(“Bob”, 25)

# Display users

Display_users()

# Update a user

Update_user(1, “Alice Johnson”, 31)

# Display users after update

Display_users()

# Delete a user

Delete_user(2)

# Display users after deletion

Display_users()

# Close the connection

Conn.close()
Output:

Table created successfully.

Inserted user: Alice, Age: 30

Inserted user: Bob, Age: 25

User Records:

(1, ‘Alice’, 30)

(2, ‘Bob’, 25)

Updated user with ID: 1

User Records:

(1, ‘Alice Johnson’, 31)

(2, ‘Bob’, 25)

Deleted user with ID: 2

User Records:

(1, ‘Alice Johnson’, 31)

Result:

The program successfully performs various database operations, including creating a


table, inserting users, updating user details, deleting a user, and displaying user records.
16(12) → Design a GUI based calculator to perform arithmetic operations like
addition,subtraction, multiplication and division. (Hint: Expression Calculator using
tk)

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

- IF Number THEN Append to Expression

- IF Operator THEN Append to Expression

- IF “=” THEN Evaluate Expression

- IF “C” THEN Reset Expression

3. EVALUATE EXPRESSION

- Parse Expression

- Apply Order of Operations (PEMDAS)

- Perform Arithmetic Operations

- 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 = [

("7", 1, 0), ("8", 1, 1), ("9", 1, 2), ("/", 1, 3),

("4", 2, 0), ("5", 2, 1), ("6", 2, 2), ("*", 2, 3),


("1", 3, 0), ("2", 3, 1), ("3", 3, 2), ("-", 3, 3),

("0", 4, 0), (".", 4, 1), ("=", 4, 2), ("+", 4, 3)

for (text, row, col) in buttons:

button = tk.Button(parent, text=text, padx=20, pady=20,

command=lambda t=text: update_display(t) if t != "=" else calculate_result())

button.grid(row=row, column=col)

clear_button = tk.Button(parent, text="C", padx=20, pady=20, command=clear_display)

clear_button.grid(row=5, column=0, columnspan=3)

parent.mainloop()
Output:

Result:

The GUI-based calculator successfully performs basic arithmetic operations (addition,


subtraction, multiplication, division) and displays results based on user input.
17(13-1) → Write a python program to read the file contents and do the following
operatios

a) Print each word of a file in reverse order.

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

1. Input line number.

2. Check existence.

3. Print line.

5. Replace String

1. Input old/new string.

2. Replace string.

3. Print updated.

Program:

Str=”welcome to the python world “

Words=str.split(“ “)

Print (words)

Words =Words[-1::-1]

Print(words)

Str1=’ ‘.join(words)

Print(str1)
Output:

[‘welcome’,’to’,’the’, ‘python’,’world’]

[‘world’, ‘python’,’the’,’to’, ‘welcome’]

RESULT:

The program reads the file contents and prints each word in reverse order.

You might also like