0 ratings 0% found this document useful (0 votes) 3 views 18 pages Full Python Programming Lab Manual
The document outlines a series of Python programming exercises designed for students at St. Joseph's Polytechnic College, focusing on various programming concepts such as finding the greatest of three numbers, summing natural numbers, string manipulation, and working with data structures like tuples, dictionaries, and arrays. Each exercise includes an aim, algorithm, program code, and expected output, demonstrating the successful implementation of the tasks. Overall, the document serves as a practical guide for students to enhance their Python programming skills.
AI-enhanced title and description
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save Full Python Programming Lab manual For Later
810 —[Link]’S POLYTECHNIC COLLEGE
KRISHNAGIRI
1052234440 - PYTHON PROGRAMMING
(2023 REGULATION)
II Year / IV" Semester
Prepared By.
Mr. ASKARALL M.E.,
HOD,
Department of Computer Engineering,
810 —St. Joseph’s Polytechnic College,
Krishnagiri.Ex. No.1 ‘Write a python program to read three numbers and print the greatest of three
Date: numbers.
Aim:
To write a Python program that reads three numbers (stored in variables a, b, and c) and prints the
greatest of the three numbers.
Algorithm:
1. Start
2. Input:
© Prompt the user to enter three numbers and store them in variables a, b, and c.
3. Comparison:
© Compare the three numbers using conditional statements:
+ Ifais greater than or equal to b and also greater than or equal to c, then ais the
greatest.
+ Else if b is greater than or equal to a and also greater than or equal to c, then b is,
the greatest.
= Otherwise, c is the greatest.
4. Output:
o Print the greatest number.
5. End
Program:
# Program to find the greatest of three numbers
# Input: Reading three numbers from the user
loat(input("Enter the first number: "))
loat(input("Enter the second number: "))
float(input("Enter the third number: "))
# Logic: Finding the greatest number
a>=banda
elif >=aand b>=c:
greatest =b
else:
greatest =
# Output: Display the greatest number
print(f"The greatest number among {a}, (b), and {c} is {greatest).")Output:
Enter the first number: 25
Enter the second number: 41
Enter the third number: 20
‘The greatest number among 25.0, 41.0, and 20.0 is 41.0.
Result;
The Python program successfully uses variables a, b, and c to read three numbers, compares them, and
prints the greatest among the three numbers,Ex. No.2 | Write a python program to find the sum of N number using range () function in for
Date: loop.
Aim
To write a Python program to calculate the sum of the first N natural numbers using the range()
function in a for loop.
Algorithm
Start
Input: Prompt the user to enter a positive integer N.
Initialize: Set a variable total_sum to 0.
Loop: Use a for loop with the range() function to iterate over numbers from 1 to N (inclusive).
o Add: Add the current number to total_sum during each iteration.
Output: Afier the loop ends, print the sum of the first N natural numbers.
End
BU pee
Program:
+# Program to find the sum of the first N natural numbers using range() in a for loop
# Step 1: Input
N= int(input("Enter a positive integer N: "))
#Step2: Initialize
total_sum = 0
# Step 3: Loop and Add
for number in range(1, N+ 1):
total_sum += number
# Step 4: Output
print(f"The sum of the first {N] natural numbers is: {total_sum}")
Output:
Enter a positive integer N: 5
‘The sum of the first 5 natural numbers is: 15
Result:
The Python program successfully calculates the sum of the first N natural numbers using the
range() function in a for loop. The program was tested and produced correct outputs for all test cases.Ex. No.3 | Write a python program to demonstrate the string slicing, concatenation, replication
Date: and len() method.
Aim
To write a Python program to demonstrate string slicing, concatenation, replication, and the len()
method.
Algorithm
Start
Define a string, str1, for demonstration purposes (e.
String Slicing:
icing techniques to extract parts of the string, such as str1[0:5] for the first 5
aracters.
4, String Concatenation:
© Define another string, str2 (e.
using the + operator.
5. String Replication:
© Replicate the string strl multiple times using the * operator.
6. Using len) Method:
© Use the len() method to calculate and print the length of strl.
Display all outputs to the user.
End
"Hello, World!").
“Welcome to Python!"), and concatenate it with str
Program
# Demonstration of string slicing, concatenation, replication, and len() method
# Step 1: Define the string
“Hello, World!"
str
# Step 2: String Slicing
sliced_part = str1[0:5] # First 5 characters
sliced_part_2=str1[7:] # From 7th character to end
+# Step 3: String Coneaten:
str2 =" Welcome to Python!"
concatenated_string = str] + str2
# Step 4: String Replication
replicated_string = strl * 3 #Replicate 3 times
+# Step 5: Using len() Method
length_of_string = len(strl)+# Output results
print("Original String:
prini("Sliced Part (0
print("Sliced Part (7 to end)", sliced_part_2)
print("Concatenated String:", concatenated_string)
print("Replicated String (3 times):", replicated_string)
print("Length of Original String:”, length_of string)
Output
Original String: Hello, World!
iced Part (0-5): Hello
sd Part (7 to end): World!
Concatenated String: Hello, World! Welcome to Python!
Replicated String (3 times): Hello, World!Hello, World!Hello, World!
Length of Original String: 13
Result;
‘The Python program successfully demonstrates the usage of string slicing, concatenation,
replication, and the len() method, providing expected outputs.Ex. No.4 | Write a python program to create a tuple and convert into a list and print the
Date: list in sorted order.
Aim
To write a Python program to create a tuple, convert it into a list, and print the list in sorted
order.
Algorithm
Start
Create a tuple with some elements.
Convert the tuple into a list using the list() funetion.
Use the sorted() function to sort the list in ascending order.
Print the original tuple, the converted list, and the sorted
» End
ay eepe
Program
#Step 1: Create a tuple
my_tuple = (23, 1, 45, 12,8, 19)
4# Step 2: Convert the tuple into a list
my_list = list(my_tuple)
4 Step 3: Sort the list
sorted _list = sorted(my_list)
# Step 4: Print the results
print("Original Tuple:", my_tuple)
print("Converted List:", my
print("Sorted List:", sorted_list)
Output:
Original Tuple: (23, 1, 45, 12, 8, 19)
Converted List: [23, 1,45, 12, 8, 19]
Sorted List: (1, 8, 12, 19, 23, 45]
Result:
‘The Python program successfully creates a tuple, converts it into a list, and prints the list in
sorted order.Ex. No.5 | Write a python program to create a dictionary and check whether a key or
Date: value exist in the dictionary.
‘To write a Python program that creates a dictionary and checks whether a key or value exists in
the dictionary.
Algorithm
= Start
Create an empty di
1
2. ry or initialize it with some predefined key-value pairs.
3. Prompt the user to input key-value pairs and update the dictionary (optional).
4. Display the dictionary to the user.
5. Prompt the user to input a key to check if'it exists in the dictionary:
© Ifthe key exists, print "Key exists in the dictio
© Otherwise, print "Key does not exist in the dictionary
6. Prompt the user to input a value to check if it exists in the dictionary:
© Ifthe value exists, print "Value exists in the dictionary”,
© Otherwise, print “Value does not exist in the
7. End
Program
the dictionary
25", "cit
my_dict = { ‘New York"}
# Step 2: Display the dictionary
print("Dictionary:
# Step 3: Check if a key exists
key_to_check = input("Enter a key to check:
if key_to_check in my_dic
print(f"Key "{key_to_check}" exis
else:
print(f"Key '{key_to_check}' does not exist in the dictionary."
)
in the dictionary.")
# Step 4: Check if a value exists
value_to_check = input("Enter a value to check: ")
if value_to_check in my_dict.values():
print(f"Value '{value_to_check}' exists in the dictionary.")else:
print(f"Value '{ value_to_check}' does not exist in the dictionary.")
Output:
Dictionary: (‘name ‘Alice’, ‘ag
Enter a key to check: name
Key ‘name’ exists in the dictionary.
Enter a value to check: 25
Value ‘25' exists in the dictionary.
25", ‘city’: 'New York'}
The program successfully creates a dictionary, checks for the existence of a key or value, and
provides accurate results.[Link].6 | Write a python program fo create one dimensional array and convert into a
Date: | 2D-dimensional array using reshape(), print the first two columns alone using
slicing.
Aim
To write a Python program to create a one-dimensional array, convert it into a two-dimensional array
using the reshape() method, and print the first two columns alone using slicing.
Algorithm
1. Step 1: Import the required library,
© Import the numpy library for array manipulation.
2. Step 2: Create a one-dimensional array.
Use [Link]() to create a one-dimensional array with some sample elements.
3. Step 3: Reshape the one-dimensional array into a two-dimensional array.
© Use the reshape() function to reshape the array into a 2D array with the desired number
of rows and columns.
4. Step 4: Print the two-dimensional array.
© Display the reshaped 2D array for verification.
5. Step 5: Slice and print the first two columns.
‘© Use slicing ({:, :2]) to extract the first two columns of the 2D array and print them.
6. Step 6: Display the output and conclude the program.
Program
import numpy as np
# Step 1: Create a one-dimensional array
one_d_array = [Link]((1, 2, 3, 4, 5, 6, 7,8, 9, 10, 11, 12])
# Step 2: Reshape the array into a two-dimensional array (4 rows, 3 columns)
‘two_d_array = one_d_array.reshape(4, 3)
# Step 3: Print the 2D array
print("Two-dimensional array:
print(two_d_array)
# Step 4: Print the first two columns of the 2D array
print("\nFirst two columns:")
print(two_d_array[:, :2))
10Output
‘Two-dimensional array:
i123]
[45 6
[789]
[1011 12))
First two column
{1 2]
[45]
(7 8]
(10 11)
Result:
The program successfully creates a one-dimensional array, converts it into a two-dimensional
array using the reshape() method, and prints the first two columns using slicing,
uu[Link].7 | Write a python program to create two-dimensional array and search for an
Date: element using where () function.
To write a Python program to create a two-dimensional array and search for an element using
the where() function from the NumPy library.
Algorithm
1. Start
© Import the NumPy library as np.
2. Input the array dimensions and elements
© Prompt the user to enter the number of rows and columns for the 2D array.
© Create a 2D array with the specified dimensions by taking user input
3. Convert the data into a NumPy array
© Use [Link]() to create the 2D array from the list of lists
4, Input the search element
Prompt the user to enter the element to search for in the array.
5. Search for the element
© Use [Link]() to find the indices of the element in the array.
© Ifthe element is found, [Link] returns a tuple of arrays containing row and column
indi
© Ifthe element is not found, the indices arrays will be empty.
6. Display the results
© Print the row and column indices of the searched element.
© Ifthe element is not found, display an appropriate message.
7. End
Program
import numpy as np
¥ Step I: Input dimensions of the array
rows = int(input( "Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))
4# Step 2: Input elements to create a 2D array
print("Enter the elements row by row:")
array = []
for i in range(rows
row = list(map(nt, input(f"Row {i+1}:").splitQ))
if len(row) != cols:
prini(f"Error: Row {i+1} must have exactly (cols) elements.")
exit(1)
[Link](row)
+# Convert to NumPy array
array_np = [Link](array)
2# Step 3: Input the element to search for
search_element = int(input("Enter the element to search for: "))
# Step 4: Use [Link]() to search for the element,
result = [Link](array_np == search_element)
# Step 5: Display the results
if result{0] size > 0:
print(f"Element {search_element} found at the following positions (row, column):")
for r, cin zip(result{0], result{1).
print(f*((r}, {c})")
else:
print(f"Blement (search_element} not found in the array.")
Output
Enter the number of rows: 3
Enter the number of columns: 3
Enter the elements row by row:
Row 1:741
Row 2:852
Row 3:9 63
Enter the element to search for:
Element 5 found at the following positions (row, column): (1, 1)
Result;
‘The program successfully creates a two-dimensional array, searches for a specified element
using the where() function, and displays the positions of the element if found.
B[Link].8 | Write a python program to create a 2D-dimensional array and demonstrate
Date: aggregation functions sum (), min () and max () in the row and column wise.
To write a Python program to create a 2D array and demonstrate aggregation functions sum(),
min(), and max() row-wise and column-wi
Step 1: Import the required library, numpy, for working with arrays.
Step 2: Create a 2D array with predefined values or by accepting user inputs.
Step
Step 4: Calculate and display:
The sum of each row and column using numpy.sum0.
© The minimum value in each row and column using [Link]()
o_ The maximum value in each row and column using [Link]()
5. Step 5: Output the results in a clear format.
eRe
Program
import numpy as np
# Step 1: Create a 2D array
array = [Link](({5, 8, 1],
(3.7.9),
[4, 6, 2])
# Step 2: Display the 2D array
print("2D Array:”)
prini(array)
# Step 3: Row-wise and column-wise aggregation functions
# Row-wise operations
sum(array, axis=1)
[Link](array, axis=1)
[Link](array, axis=1)
row_sum.
row_min
row_max
#Column-wise operations
col_sum = [Link](array, axis
col_min = [Link](array, axis=0)
ccol_max = [Link](array, axis=0)
# Step 4: Display the results
print("\nRow-wise Results:")
print("Sum of rows:”, row_sum)
rint("Minimum of rows
print" Maximum of rows:",
4print("\nColumn-wise Results:")
print("Sum of columns:", col_sum)
print("Minimum of columns:", col_min)
print("Maximum of columns:", col_max)
Output
2D Array:
(581)
B79]
(46 2]]
Row-wise Results
Sum of rows: [14 19 12]
Minimum of rows: [1 3 2]
Maximum of rows: [8 9 6]
Column-wise Results:
Sum of columns: [12 21 12]
Minimum of columns: [3 6 1]
Maximum of columns: [5 8 9]
Result:
The Python program successfully created a 2D array and demonstrated the use of aggregation
functions sum(, min), and max() row-wise and column-wise.Hse? © | Write a python program to read a text file and write the content in another file
To read the content from a text file and write it to another text file using Python,
Algorithm:
Open the source file in read mode.
(Open the destination file in write mode.
Read the content of the source file
‘Write the content to the destination file.
Close both the source and destination files.
End.
Program
# Open the source file in read mode
le = open [Link],'r')
source_{
# Open the destination file in write mode
destination_file = opent [Link],'w’)
# Read content from source file
content = source_file.read()
# Write content to destination file
destination_file.write(content)
# Close both files
source_file.close()
destination_file.close()
print("Content has been copied successfully from [Link] to [Link].”)
Output
[Link]
Hi
Welcome to Department of Computer Engineering.
# [Link]
Hi,
Welcome to Department of Computer Engineering.
Content has been copied successfully from [Link] to [Link].
Result:
The program successfully reads the content from [Link] and writes it to [Link]. It
demonstrates how to open files, read data, and write data in Python.
16Date: Write a python program to read a esy file using pandas and print the content,
To read and display the contents of a CSV file using the pandas library in Python,
Algorithm:
1. Import pandas: Import the pandas library, which provides functions to handle data in CSV
format.
2. Read the CSV File: Use the read_csv() function from pandas to read the CSV file into a
DataFrame.
3. Display the Content: Print the content of the DataFrame using the print() function.
Program
4# Importing the pandas library
import pandas as pd
#Reading the CSV file into a DataFrame
file_path = '[Link]’ # Replace with the path to your CSV file
data = pd.read_csv(file_path)
+# Printing the content of the CSV file
print(data)
Input
#[Link]
aR: sere ae ee
» - woes
CYA cee he lle jap ae be Re a
te eae a: wa emia ok oles coomrerte ct Di Tae ee
era Se ee a nna eer
ar
a < i iia
v7Output
[Link] REGNO NAME Attendance
o 4 23500949 KATHIRESAN S 40.00
1 223500953» LOURDU SAMY A 73.33
2 3 24500975 ANTHONY RUBAN L. 6.67
3. 4 24500977 ARAVINTH K 86.67
4 5 24500980 ARUNPANDIANR, 93.33
5 6 24500981 ASARATHI. 73.33
Result:
The Python program successfully reads the contents of the CSV file using pandas and prints
the data in tabular form.
18