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

Python Programming Lab Manual

The document is a lab manual for the Python Programming course at Avanthi Institute of Engineering and Technology, detailing course objectives, prerequisites, and a weekly schedule of programming tasks. It covers fundamental programming concepts, data types, and various Python operations, including arithmetic, string manipulation, and date formatting. The manual also includes installation instructions for Python and its environment, emphasizing the ease of setup and usability for both beginners and advanced users.

Uploaded by

varunsanapathi
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)
2 views48 pages

Python Programming Lab Manual

The document is a lab manual for the Python Programming course at Avanthi Institute of Engineering and Technology, detailing course objectives, prerequisites, and a weekly schedule of programming tasks. It covers fundamental programming concepts, data types, and various Python operations, including arithmetic, string manipulation, and date formatting. The manual also includes installation instructions for Python and its environment, emphasizing the ease of setup and usability for both beginners and advanced users.

Uploaded by

varunsanapathi
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

AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY

(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING(CSE)

Python Programming
Lab Manual
(1YEAR –II SEMISTER)

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

R25ES19
Python Programming Lab 0021
(Common to all Branches)

Prerequisites: Students should install Python on Linux platform


Course Objectives:
1. To be able to introduce core programming basics and program design with functions
using Python programming language.
2. To understand a range of Object-Oriented Programming, as well as in-depth data and
information processing techniques.
3. To understand the high-performance programs designed to strengthen the practical expertise.

At the end of the course, students will be able to:

Board of Studies: Computer Science and Engineering.


Approved in BOS No: 01, 12-09-2025
Approved in ACM No: 01, 26-09-2025

Developing the following programs:


Week1:
1. Write a program to demonstrate different number data types in Python.
2. Write a program to perform different Arithmetic Operations on numbers in Python.
Week2:
3. Write a program to create, concatenate and print a string and accessing sub-string from a given
string.
4. Write a python script to print the current date in the following format “Sun May 29 02:26:23 IST
2017
Week3:
5. Write a program to create, append, and remove lists in python.
6. Write a program to demonstrate working with tuples in python.
Week4:
7. Write a program to demonstrate working with dictionaries in python.

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]
8. Write a python program to find largest of three numbers.
Week5:
9. Write a Python program to convert temperatures to and from Celsius, Fahrenheit. [ Formula: c/5
= f-32/9 ]
Week6:
10. Write a Python program to construct the following pattern, using a nested for loop
*
**
***
****
*****
****
***
**
*
11. Write a Python script that prints prime numbers less than 20.
Week7:
12. Write a python program to find factorial of a number using Recursion.
Week8:
13. Write a program that accepts the lengths of three sides of a triangle as inputs. The program
output should indicate whether or not the triangle is a right triangle (Recall from the
Pythagorean Theorem that in a right triangle, the square of one side equals the sum of the
squares of the other two sides).
Week9:
14. Write a python program to define a module to find Fibonacci Numbers and import the module
to another program.
Week10:
15. Write a python program to define a module and import a specific function in that module
to another program.
Week11
16. Write a script named [Link]. This script should prompt the user for the names of two
text files. The contents of the first file should be input and written to the second file.
Week12
17. Write a program that inputs a text file. The program should print all of the unique words in
the file in alphabetical order.
Week13:
18. Write a Python class to convert an integer to a roman numeral.
Week14:
19. Write a Python class to implement pow(x, n)
Week15:
20. Write a Python class to reverse a string word by word.

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

Introduction to Python:

Python is a high-level, interpreted, object-oriented programming language created by Guido van


Rossum. It is easy to learn, simple to read, and widely used for:

Web development , Data Science , Machine Learning , Artificial Intelligence, Automation,


Software development

Python is a portable language, which means the same code can run on Windows, Linux, and
macOS.

The official Python beginner guide notes that installation is usually straight forward across
platforms.

Need for Installation:

To write and run Python programs, we need to install:

Python Interpreter
IDLE (Python Editor)
pip (Package Installer)

A standard installation from [Link] includes the interpreter and IDLE on major desktop
platforms.

Steps to Install Python on Windows:


1) Download Python
Open the official website: [Link]/downloads
Click Download Python
Choose latest Python 3 version
2) Run Installer
Double-click the downloaded .exe file

Click “Add Python to PATH” Click Install Now

This PATH step is important so python works from Command Prompt.

3) Finish Installation

After installation completes, click Close

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

Verify Installation:
Open Command Prompt and type: python --version
Output example:
Python 3.12.3

You can also start Python shell:

python

Output:

>>>
Using IDLE:

After installation:

Open Start Menu


Search IDLE
Click IDLE (Python 3.x)

IDLE is Python’s built-in editor used to write and run programs.

First Python Program:


print("Hello, Python")

Output:
Hello, Python

Advantages of Python Installation:


Easy setup
Free and open source
Supports multiple platforms
Large standard library
Useful for beginners and advanced users

Conclusion:

Python installation is simple and user-friendly.


Once installed, we can use IDLE, Command Prompt, or IDEs like VS Code / PyCharm to write
Python programs.

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

WEEK – 1

Aim: Program to demonstrate different number data types in Python.

Description
Python supports various numeric data types to store numbers of different kinds. The commonly
used number data types are int, float, and complex.

• int is used to store whole numbers


• float is used to store decimal values
• complex is used to store numbers with real and imaginary parts

This program demonstrates the creation and usage of different number data types and displays their
values and types.

Algorithm:

1. Start
2. Declare variables of type integer, float, and complex
3. Print the values of the variables
4. Display the data type of each variable using type()
5. End

Flowchart:

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

Program
# Integer data type
a = 20

# Float data type


b = 12.56

# Complex data type

c=3+4j
print("Integer value:", a)
print("Type:", type(a))

print("Float value:", b)
print("Type:", type(b))

print("Complex value:", c)
print("Type:", type(c))

Output
Integer value: 20
Type: <class 'int'>
Float value: 12.56
Type: <class 'float'>
Complex value: (3+4j)
Type: <class 'complex'>

Result
Thus, the Python program to demonstrate different number data types was executed successfully.

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

2. Write a program to perform different Arithmetic Operations on numbers in Python.

Aim: Program to perform different arithmetic operations on numbers in Python.

Description
Arithmetic operations are basic mathematical operations performed on numbers. Python provides
arithmetic operators such as addition, subtraction, multiplication, division, modulus, and
exponentiation.
This program takes two numbers and performs different arithmetic operations using Python
operators.

Algorithm

1. Start
2. Input two numbers
3. Calculate addition, subtraction, multiplication, and division
4. Calculate modulus and exponentiation operations
5. Print the output
6. End

Flowchart

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

Program

# Assigning values
a = int(input(“Enter the Number : “))
b = int(input(“Enter the Number : “))

# Arithmetic operations
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)

Output
Enter the Number: 10
Enter the Number: 5
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Modulus: 0
Exponentiation: 100000

Result
Thus, the Python program to perform different arithmetic operations on numbers was executed
successfully.

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

WEEK-2

3. Write a program to create, concatenate and print a string and accessing sub-string from a
given string.

Aim: To write a Python program to create, concatenate, and print strings and to access sub-strings from a
given string.

Description
A string in Python is a sequence of characters enclosed in single quotes, double quotes, or triple quotes.

We create two strings


Concatenate them using + operator
Print the combined string
Access a substring using slicing
Display the result

Algorithm

1. Start
2. Input two string variables
3. Print the first string and second string
4. Print the concatenation string using + operator
5. Print the sub-strings using slicing
6. End

Flowchart

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]
Program
s=input("Enter first String : ")
s1=input("Enter second String : ")
print("First string is : ",s)
print("Second string is : ",s1)
print("concatenations of two strings :",s+s1)
#accessing of string
print("Substring of given string : ",s[1:4])
print("Reverse of given string: ",s[::-1])
print("Character at Index 3: ",s[3])
Output
Enter first String : HELLO
Enter second String : WORLD
First string is : HELLO
Second string is : WORLD
concatenations of two strings : HELLOWORLD
Substring of given string : ELL
Reverse of given string: OLLEH
Character at Index 3: L

Result

Thus, the Python program to create, concatenate, print strings, and access sub-strings was executed
successfully.

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]
4. Write a python script to print the current date in the following format “Sun May 29
02:26:23 IST 2017

Aim: To write a Python script to print the current date in the format
“Sun May 29 02:26:23 IST 2017”.

Description
This program prints the current system date and time in the required format using Python’s
datetime module and the strftime() method.
strftime() converts the current date-time object into a formatted string using format codes like:

• %a → short day name


• %b → short month name
• %d → day
• %H → hour
• %M → minute
• %S → second
• %Z → timezone
• %Y → year

Algorithm

1. Start
2. Import the time module
3. Get the current local time using localtime()
4. Format the date using strftime()
5. Print the formatted date
6. End

Flowchart

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]
Program

import time

# Get current local time


current_time = [Link]()

# Format and print date


formatted_date = [Link]("%a %b %d %H:%M:%S IST %Y", current_time)
print(formatted_date)

Output

Sun May 29 02:26:23 IST 2017

(Output varies based on current system date and time)

Result

Thus, the Python script to display the current date in the specified format was executed
successfully.

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

WEEK-3

5. List Operations (Create, Append, Remove)

Aim
To write a Python program to create a list, append elements, and remove elements using user input.

Description
A list in Python is a collection type used to store multiple values in a single variable. Lists
are ordered, changeable, and allow duplicate values.
In this program, we perform the following operations:

Create a list
Append a new element using append()
Remove an element using remove()
Print the final list

Algorithm

1. Start
2. Create an empty list
3. Read number of elements from user
4. Add elements to list
5. Append a new element
6. Remove an element
7. Display final list
8. End

Flowchart
Start

Create empty list

Input elements

Append element

Remove element

Display list

End

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.

Program

# Create list using user input

n = int(input("Enter number of elements: "))


lst= [ ]

for i in range(n):
val = int(input("Enter element: "))
[Link](val)

print("Original List:", lst)

# Append
new_val = int(input("Enter element to append: "))
[Link](new_val)
print("After Append:", lst)

# Remove
rem = int(input("Enter element to remove: "))
[Link](rem)
print("After Removal:", lst)

Output
Enter number of elements: 3
Enter element: 20
Enter element: 30
Enter element: 40
Original List: [20, 30, 40]
Enter element to append: 40
After Append: [20, 30, 40, 40]
Enter element to remove: 20
After Removal: [30, 40, 40]

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

6. Tuple Operations

Aim:To demonstrate tuple operations in Python.

Description
A tuple in Python is a collection data type used to store multiple values in a single variable.
Tuples are:

Ordered
Immutable (cannot be changed after creation)
Allow duplicate values

In this program, we perform basic tuple operations:

Create a tuple
Access tuple elements using index
Concatenate two tuples
Print the results

Algorithm

1. Start
2. Read elements from user
3. Store in tuple
4. Display tuple
5. Access elements
6. End

Flowchart

Start

Input elements

Convert to tuple

Display operations

End

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

Program
n = int(input("Enter number of elements: "))
temp = [ ]

for i in range(n):
[Link](input("Enter element: "))

tup = tuple(temp)

print("Tuple:", tup)
print("First element:", tup[0])
print("Length:", len(tup))

Output
Enter number of elements: 3
Enter element: abc
Enter element: def
Enter element: ghi
Tuple: ('abc', 'def', 'ghi')
First element: abc
Length: 3

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

WEEK-4

7. Dictionary Operations

Aim:To demonstrate dictionary creation and operations.

Description
A dictionary in Python is a collection data type used to store data in key–value pairs.

Features of dictionary:

• Mutable (can be changed)


• Stores values with keys
• No duplicate keys allowed
• Fast data access using keys

Algorithm

1. Start
2. Create empty dictionary
3. Read key-value pairs
4. Add new pair
5. Remove key
6. Display dictionary
7. End

Flowchart

Start

Create dictionary

Input key-value pairs

Add/Remove items

Display dictionary

End

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

Program
d = {}

n = int(input("Enter number of items: "))

for i in range(n):
key = input("Enter key: ")
value = input("Enter value: ")
d[key] = value

print("Dictionary:", d)

# Add item
k = input("Enter new key: ")
v = input("Enter value: ")
d[k] = v

# Remove item
rem = input("Enter key to remove: ")
[Link](rem)

print("Updated Dictionary:", d)

Output

Enter number of items: 3


Enter key: 1
Enter value: cse
Enter key: 2
Enter value: csm
Enter key: 3
Enter value: csd
Dictionary: {'1': 'cse', '2': 'csm', '3': 'csd'}
Enter new key: 4
Enter value: ece
Enter key to remove: 4
Updated Dictionary: {'1': 'cse', '2': 'csm', '3': 'csd'}

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

8. Largest of Three Numbers

Aim:To find the largest of three numbers using user input.

Description

This program finds the largest among three given numbers using if-elif-else statements.
The program:

1. Takes three numbers as input


2. Compares them
3. Prints the largest number

Algorithm

1. Start
2. Input three numbers
3. Compare using if-else
4. Display largest
5. End

Flowchart
Start

Input a, b, c

Compare

Print largest

End

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]
Program

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

if a >= b and a >= c:


largest = a
elif b >= a and b >= c:
largest = b
else:
largest = c

print("Largest number is:", largest)

Output
Enter first number: 55
Enter second number: 22
Enter third number: 33
Largest number is: 55

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

WEEK-5

9. Temperature Conversion (Celsius ↔ Fahrenheit)

Aim: To convert temperature between Celsius and Fahrenheit.

Description:
Temperature conversion is the process of converting a temperature value from one scale to
another. The two commonly used temperature scales are Celsius (°C) and Fahrenheit (°F).
In this program, the user enters a temperature value and selects the type of conversion:

• Celsius to Fahrenheit
• Fahrenheit to Celsius

The program uses the standard mathematical formulas:

Algorithm

1. Start
2. Input choice
3. If Celsius → Fahrenheit, apply formula
4. Else Fahrenheit → Celsius
5. Display result
6. End

Flowchart

Start

Enter choice

C→F or F→C

Apply formula

Display result

End

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

Program

print("1. Celsius to Fahrenheit")


print("2. Fahrenheit to Celsius")

choice = int(input("Enter choice: "))

if choice == 1:
c = float(input("Enter Celsius: "))
f = (c * 9/5) + 32
print("Fahrenheit:", f)

elif choice == 2:
f = float(input("Enter Fahrenheit: "))
c = (f - 32) * 5/9
print("Celsius:", c)

else:
print("Invalid choice")

Output:

1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
Enter choice: 1
Enter Celsius: 25
Fahrenheit: 77.0

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

WEEK-6

10. Star Pattern using Nested for Loop

Aim:To write a Python program to construct a star (*) pattern using nested for loops.

Description

This program prints a star (*) pattern using nested for loops.
The outer loop controls the number of rows
The inner loop prints stars in each row
Nested loops are useful for pattern generation problems.
This example prints a right-angle triangle star pattern.

Algorithm

1. Start
2. Input number of rows (n)
3. Use loop from 1 to n → print increasing stars
4. Use loop from n-1 to 1 → print decreasing stars
5. Stop

Flowchart
Start

Input n

For i = 1 to n
Print * i times

For i = n-1 to 1
Print * i times

Stop

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]
Program
n = int(input("Enter number of rows: "))

# Increasing pattern
for i in range(1, n + 1):
for j in range(i):
print("*", end=" ")
print()

# Decreasing pattern
for i in range(n - 1, 0, -1):
for j in range(i):
print("*", end=" ")
print( )

Output:
Enter number of rows: 5
*
**
***
****
*****
****
***
**
*

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

11. Prime Numbers Less Than 20

Aim : To write a Python program to print all prime numbers less than 20.
Description

A prime number is a number greater than 1 that has only two factors: 1 and itself.
This program prints all prime numbers less than 20 using a loop and conditional statements.

The logic:
Check each number from 2 to 19
Test whether it is divisible by any smaller number
If not divisible, it is a prime number

Algorithm

1. Start
2. Print "Prime numbers less than 20 are:"
3. Set n = 20
4. Repeat for num from 0 to n-1
5. If num > 1 then
6. Check i from 2 to num-1
7. Else print num
8. Repeat until loop ends
9. Stop

Flowchart

Start

Set n=20

Repeat for num from 0 to n-1

If num>1 then → print

Check i from 2 to num-1

If num % i ==0 then break

Else print num

Repeat unitl loop ends

End

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

Program

print("Prime numbers less than 20 are:")


n=20
for num in range(n):
# prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num, end=" ")

Sample Output
Prime numbers less than 20 are:
2 3 5 7 11 13 17 19

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

WEEK-7

12. Write a python program to find factorial of a number using


Recursion. Factorial using Recursion

Aim:To Write a python program to find factorial of a number using Recursion.


Factorial using Recursion

Definition
Factorial of a number n is the product of all positive integers less than or equal to n.
n!=n×(n−1)×(n−2)×⋯×1n! = n \times (n-1) \times (n-2) \times \dots \times
1n!=n×(n−1)×(n−2)×⋯×1

Recursion
Recursion means a function calls itself until a base condition is met.
To

Algorithm

1. Start
2. Define recursive function factorial(n)
3. If n == 0 or n == 1, return 1 (base case)
4. Else return n * factorial(n-1)
5. Print result
6. Stop

Flow Chart

Start

Input number n

Call factorial(n)

Is n == 0 or n == 1 ?

Yes → Return 1

No → Return n × factorial(n-1)

Print factorial

Stop

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

Program:

def factorial(n):
if n == 0 or n == 1: # Base condition
return 1
else:
return n * factorial(n-1) # Recursive call

# Input from user


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

if num < 0:
print("Factorial does not exist for negative numbers")
elif num==0:
print("factorial of num is 1")
else:
result = factorial(num)
print("Factorial of", num, "is", result)

Output:
Enter a number: 5
Factorial of 5 is 120

factorial(5)
= 5 * factorial(4)
= 5 * 4 * factorial(3)
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 * factorial(1)
=5*4*3*2*1
= 120

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

WEEK-8

13. Write a program that accepts the lengths of three sides of a triangle as inputs. The
program
output should indicate whether or not the triangle is a right triangle (Recall from the
Pythagorean Theorem that in a right triangle, the square of one side equals the sum of the
squares of the other two sides).

Aim: To Write a program that accepts the lengths of three sides of a triangle as inputs. The
program
output should indicate whether or not the triangle is a right triangle (Recall from the
Pythagorean Theorem that in a right triangle, the square of one side equals the sum of the
squares of the other two sides).

Algorithm

1. Start
2. Input three sides i,j,k
3. Arrange sides so the largest side is c
4. Check whether a² + b² = c²
5. If true, print Right Triangle
6. Else print Not a Right Triangle
7. Stop

Program

# Program to check whether a triangle is a right triangle

i = float(input("Enter first side: "))


j = float(input("Enter second side: "))
k = float(input("Enter third side: "))

# Find the largest side


sides =sorted([i, j, k])
a,b,c=sides

# Check Pythagorean theorem


if c**2 == a**2 + b**2:
print("It is a right triangle")
else:
print("It is not a right triangle")

Output:
Enter first side: 3
Enter second side: 4
Enter third side: 5
It is a right triangle

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

WEEK-9

14. Write a python program to define a module to find Fibonacci Numbers and import the
module to another program.

Aim: To Write a python program to define a module to find Fibonacci Numbers and import the module to
another program.

Algorithm: [Link]
1. Start
2. Input n Enter how many Fibonacci numbers
3. Call fibo(n)
4. End

[Link]
1. Start
2. Integer Variables n1=0, n2=1
3. Print “Fibonacci Series”
4. Set i=0
5. Repeat for i form 0 to n-1
6. Print n1,
7. repeat n1=n2, n2=n1+n2
8. Increment i++
9. Print newline
10. Return to main
11. End
Flow Chart

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

Program:
1) Create a module file → [Link]
# [Link]
def fibo(n):
n1 = 0
n2 = 1
print("Fibonacci Numbers:")
for i in range(n):
print(n1, end=" ")
n1, n2 = n2, n1 + n2
print()

2) Create another program to import the module → [Link]

# [Link]
import fibonacci
n = int(input("Enter upto how many Fibonacci numbers do you want? "))
[Link](n)

Output:

Enter upto how many Fibonacci numbers do you want? 5


Fibonacci Numbers:
01123

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]
WEEK-10

15. Write a python program to define a module and import a specific function in that module to
another program

Aim: To Write a python program to define a module and import a specific function in that module
to another program

Algorithm: [Link]
1. Start
2. define function add(a,b)
3. return a+b
4. define function sub(a,b)
5. return a-b
6. End

Algorithm: [Link]
[Link]
2. import function add from module
3. Input x,y
4. call function add(x,y) and store in value result
5. Print result
6. End

Flow Chart:

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

Program.
1) Module file → [Link]

Save this as [Link]

# [Link]

def add(a, b):


return a + b

def sub(a, b):


return a - b

2) Another program to import specific function → [Link]

Here we import only the add() function

# [Link]

from mymodule import add

x = int(input("Enter first number: "))


y = int(input("Enter second number: "))
result = add(x, y)
print("Sum =", result)

Output
Enter first number: 20
Enter second number: 30
Sum = 50

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

WEEK-11

16. Write a script named [Link]. This script should prompt the user for the names of two
text files. The contents of the first file should be input and written to the second file.

Aim: To Write a script named [Link]. This script should prompt the user for the names of two
text files. The contents of the first file should be input and written to the second file.

Description
This program copies the contents of one text file into another text file.
The script:

1. Prompts the user for source file name


2. Prompts for destination file name
3. Opens the source file in read mode
4. Reads all contents
5. Opens the destination file in write mode
6. Writes the copied contents into the second file

This is a basic file handling program in Python.

Algorithm

1. Start
2. Input source file name
3. Input destination file name
4. Open source file in read mode
5. Read file contents
6. Open destination file in write mode
7. Write contents into destination file
8. Print file copied successfully
9. End

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]
Flow Chart:

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

Program: [Link]

# [Link]

# Prompt user for source and destination file names


try:
source_file = input("Enter source file: ")
destination_file = input("Enter destination file: ")

with open(source_file, "r") as infile:


data = [Link]()

with open(destination_file, "w") as outfile:


[Link](data)

print("File copied successfully!")

except FileNotFoundError:
print("Source file not found.")
except Exception as e:

print("Error:", e)

How it works

1. Takes two file names from the user:


o Source file → file to copy from
o Destination file → file to copy into
2. Reads all text from the source file
3. Writes the same text into the destination file
4. Displays success message

Example Run
Enter the source file name: [Link]
Enter the destination file name: [Link]
File copied successfully!

If [Link] contains:

Hello Python
Welcome to File Handling

Then [Link] will contain the same text.

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

17. Write a program that inputs a text file. The program should print all of the unique
words in the file in alphabetical order.

Aim: program that inputs a text file. The program should print all of the unique words in the file
in alphabetical order.

Description

This program reads a text file, finds all the unique words, and prints them in alphabetical order.
The logic:

• Read all text from the file


• Split text into words
• Use set() to remove duplicate words
• Use sorted() to arrange words alphabetically
• Print each word

This program is useful for file handling and string processing.

Algorithm

1. Start
2. Input file name
3. Open file in read mode
4. Read all text from file
5. Split text into words
6. Remove duplicates using set()
7. Sort words using sorted()
8. Print unique words
9. Stop

Flow Chart:
Start

Input File Name

Open File in Read Mode

Read File Content

Split Text into Words

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]
Remove Duplicate Words using set()

Sort Words Alphabetically

Print Each Word

Stop

Program: Unique Words in Alphabetical Order


# Program to print unique words from a file in alphabetical order

filename = input("Enter the file name: ")

with open(filename, "r") as file:


text = [Link]()

# Convert text into words


words = [Link]()

# Use set to store unique words


unique_words = set(words)

# Print words in alphabetical order


for word in sorted(unique_words):
print(word)

How it works

1. Opens the file


2. Reads all text using read()
3. Splits text into words using split()
4. Uses set() to remove duplicate words
5. Uses sorted() to arrange words in alphabetical order
6. Prints each word

Example Input File ([Link])


python is easy python is powerful and easy

Output
Enter the file name: [Link]
and
easy
is
powerful
python

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

Better Version (Ignore Case + Remove Punctuation)


import string

filename = input("Enter file name: ")

with open(filename, "r") as file:


text = [Link]().lower()

# Remove punctuation
for ch in [Link]:
text = [Link](ch, "")

words = [Link]()
unique_words = sorted(set(words))

print("Unique words in alphabetical order:")


for word in unique_words:
print(word)

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

WEEK 13

18. Write a Python class to convert an integer to a roman numeral.

Aim: Python class to convert an integer to a roman numeral.

Description

This program uses a Python class to convert an integer number into a Roman numeral.

Roman numerals use symbols such as:

I=1
V=5
X = 10
L = 50
C = 100
D = 500
M = 1000

The program repeatedly subtracts the largest possible value from the given number and adds the
corresponding Roman symbol to the result.

Example:

58 = LVIII

Algorithm

1. Start
2. Create class RomanConverter
3. Define method int_to_roman(num)
4. Store integer values and Roman symbols in lists
5. Compare input number with values
6. Append matching Roman symbol
7. Subtract value from number
8. Repeat until number becomes 0
9. Print Roman numeral
10. Stop

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]
Flow Chart:
Start

Create Class RomanConverter

Input Integer Number

Store Values and Symbols

Compare Number with values

Append Roman Symbol

Subtract Value from Number

Is Number = 0?

No → Repeat Compare Step

Yes → Print Roman Numeral

Stop

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

Program:
class RomanConverter:
def int_to_roman(self, num):
# List of values and their corresponding Roman numerals
values = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4, 1
]

symbols = [
"M", "CM", "D", "CD",
"C", "XC", "L", "XL",
"X", "IX", "V", "IV", "I"
]

roman = ""

for i in range(len(values)):
while num >= values[i]:
roman += symbols[i]
num -= values[i]

return roman

# Create object
converter = RomanConverter()

# Input from user


number = int(input("Enter an integer: "))

# Convert and display result


print("Roman Numeral:", converter.int_to_roman(number))

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

How it works

• Uses two lists:


o values → integer values
o symbols → corresponding Roman numerals
• Repeatedly subtracts the largest possible value
• Appends the corresponding symbol to result

Example Output
Enter an integer: 58
Roman Numeral: LVIII
Enter an integer: 1994
Roman Numeral: MCMXCIV

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

WEEK14:

19. Write a Python class to implement pow(x, n)

Aim: Python Class to Implement pow(x, n)

Description

This program uses a Python class to implement the power function pow(x, n), which calculates:
xnx^nxn
where:
• x = base value
• n = exponent (power)

The class contains a method that multiplies the base value x exactly n times using a loop.
Example:
pow(2, 3) = 2 × 2 × 2 = 8

Algorithm

1. Start
2. Create a class Power
3. Define method pow(x, n)
4. Initialize result = 1
5. Repeat multiplication n times
6. Return result
7. Print the final answer
8. Stop

Flow Chart
Start

Create Class Power

Input x, n

Set result = 1

Repeat loop n times

Multiply result = result × x

Print result

End

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

Program: Python Class to Implement pow(x, n)


class Power:
def pow(self, x, n):
return x ** n

# Create object
obj = Power()

# Input values
x = int(input("Enter base value: "))
n = int(input("Enter exponent value: "))

# Display result
print("Result:", [Link](x, n))

Example Output
Enter base value: 2
Enter exponent value: 5
Result: 32

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

WEEK15:

20. Write a Python class to reverse a string word by word.

Aim: Python class to reverse a string word by word

Description
This program uses a Python class to reverse a string word by word.
First, the input string is split into individual words using split()
The list of words is reversed using slicing [::-1]
The reversed words are joined back into a string using join()

This is useful for string manipulation and text processing.

Example:
"Python is easy" → "easy is Python"

Algorithm
Start
Create a class ReverseWords
Define a method to split the string into words
Reverse the list of words
Join the reversed words into a string
Return the result
Print the reversed string
Stop

Flow chart
Start

Create Class ReverseWords

Define method reverse_word_by_word()

Input string

Split string into words

Reverse word list

Join reversed words

Print result

End

Avanthi Institute of Engineering and Technology (Autonomous)


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A I C T E, New Delhi & Permanently Affiliated to JNTU-GV, Vizianagaram)
Accredited by NAAC “A+” Grade
Cherukupally (Village), Near Tagarapuvalasa Bridge, Vizianagaram (Dist), AP, Pin-531 162.
principal@[Link], [Link]

Program:

class ReverseWords:
def reverse_word_by_word(self, text):
# Split sentence into words
words = [Link]()

# Reverse word order


reversed_words = words[::-1]

# Join words back into string


return " ".join(reversed_words)

# Create object
obj = ReverseWords()

# Input from user


string = input("Enter a string: ")

# Display reversed string


print("Reversed string:", obj.reverse_word_by_word(string))

Output:
Enter a string: Python is easy
Reversed string: easy is Python

Avanthi Institute of Engineering and Technology (Autonomous)

You might also like