0% found this document useful (0 votes)
25 views18 pages

Full Python Programming Lab Manual (1-10)

The document outlines a series of Python programming exercises for students at the Government Polytechnic College, focusing on various programming concepts such as finding the greatest of three numbers, calculating the sum of natural numbers, string manipulation, tuple and list conversion, dictionary operations, and working with arrays using NumPy. Each exercise includes an aim, algorithm, program code, output examples, and results indicating successful execution. The exercises are designed to enhance students' understanding of Python programming and its applications.

Uploaded by

hsumi173028
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)
25 views18 pages

Full Python Programming Lab Manual (1-10)

The document outlines a series of Python programming exercises for students at the Government Polytechnic College, focusing on various programming concepts such as finding the greatest of three numbers, calculating the sum of natural numbers, string manipulation, tuple and list conversion, dictionary operations, and working with arrays using NumPy. Each exercise includes an aim, algorithm, program code, output examples, and results indicating successful execution. The exercises are designed to enhance students' understanding of Python programming and its applications.

Uploaded by

hsumi173028
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
You are on page 1/ 18

128 – GOVERNMENT POLYTECHNIC COLLEGE

Arakandanallur, Villupuram District.

Department of Computer Engineering

1052234440 - PYTHON PROGRAMMING

(2023 REGULATION)
II Year / IVth Semester

Prepared By,
Mr.Daison Raj, M.E.,
Lecturer,
Department of Computer Engineering,
128 – Government Polytechnic College,
Villupuram.

1
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:
o Prompt the user to enter three numbers and store them in variables a, b, and c.
3. Comparison:
o Compare the three numbers using conditional statements:
 If a is greater than or equal to b and also greater than or equal to c, then a is 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


a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
c = float(input("Enter the third number: "))

# Logic: Finding the greatest number


if a >= b and a >= c:
greatest = a
elif b >= a and b >= c:
greatest = b
else:
greatest = c

# Output: Display the greatest number


print(f"The greatest number among {a}, {b}, and {c} is {greatest}.")

2
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.

3
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

1. Start
2. Input: Prompt the user to enter a positive integer N.
3. Initialize: Set a variable total_sum to 0.
4. 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.
5. Output: After the loop ends, print the sum of the first N natural numbers.
6. End

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

# Step 2: 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.

4
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

1. Start
2. Define a string, str1, for demonstration purposes (e.g., "Hello, World!").
3. String Slicing:
o Use slicing techniques to extract parts of the string, such as str1[0:5] for the first 5
characters.
4. String Concatenation:
o Define another string, str2 (e.g., " Welcome to Python!"), and concatenate it with str1
using the + operator.
5. String Replication:
o Replicate the string str1 multiple times using the * operator.
6. Using len() Method:
o Use the len() method to calculate and print the length of str1.
7. Display all outputs to the user.
8. End

Program

# Demonstration of string slicing, concatenation, replication, and len() method

# Step 1: Define the string


str1 = "Hello, World!"

# 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 Concatenation


str2 = " Welcome to Python!"
concatenated_string = str1 + str2

# Step 4: String Replication


replicated_string = str1 * 3 # Replicate 3 times

# Step 5: Using len() Method


length_of_string = len(str1)

5
# Output results
print("Original String:", str1)
print("Sliced Part (0-5):", sliced_part)
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!
Sliced Part (0-5): Hello
Sliced 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.

6
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

1. Start
2. Create a tuple with some elements.
3. Convert the tuple into a list using the list() function.
4. Use the sorted() function to sort the list in ascending order.
5. Print the original tuple, the converted list, and the sorted list.
6. End

Program
# Step 1: Create a tuple
my_tuple = (23, 1, 45, 12, 8, 19)

# Step 2: Convert the tuple into a list


my_list = list(my_tuple)

# Step 3: Sort the list


sorted_list = sorted(my_list)

# Step 4: Print the results


print("Original Tuple:", my_tuple)
print("Converted List:", my_list)
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.

7
Ex. No. 5 Write a python program to create a dictionary and check whether a key or
Date: value exist in the dictionary.

Aim

To write a Python program that creates a dictionary and checks whether a key or value exists in
the dictionary.

Algorithm

1. Start
2. Create an empty dictionary 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:
o If the key exists, print "Key exists in the dictionary".
o 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:
o If the value exists, print "Value exists in the dictionary".
o Otherwise, print "Value does not exist in the dictionary".
7. End

Program

# Step 1: Initialize the dictionary


my_dict = {"name": "Alice", "age": "25", "city": "New York"}

# Step 2: Display the dictionary


print("Dictionary:", my_dict)

# Step 3: Check if a key exists


key_to_check = input("Enter a key to check: ")
if key_to_check in my_dict:
print(f"Key '{key_to_check}' exists in the dictionary.")
else:
print(f"Key '{key_to_check}' does not exist 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.")

8
else:
print(f"Value '{value_to_check}' does not exist in the dictionary.")
Output:

Dictionary: {'name': 'Alice', 'age': '25', 'city': 'New York'}


Enter a key to check: name
Key 'name' exists in the dictionary.
Enter a value to check: 25
Value '25' exists in the dictionary.

Result:

The program successfully creates a dictionary, checks for the existence of a key or value, and
provides accurate results.

9
Ex. No. 6 Write a python program to 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.


o Import the numpy library for array manipulation.
2. Step 2: Create a one-dimensional array.
o Use numpy.array() to create a one-dimensional array with some sample elements.
3. Step 3: Reshape the one-dimensional array into a two-dimensional array.
o 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.
o Display the reshaped 2D array for verification.
5. Step 5: Slice and print the first two columns.
o 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 = np.array([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])

10
Output

Two-dimensional array:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]

First two columns:


[[ 1 2]
[ 4 5]
[ 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.

11
Ex. No. 7 Write a python program to create two-dimensional array and search for an
Date: element using where () function.

Aim

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
o Import the NumPy library as np.
2. Input the array dimensions and elements
o Prompt the user to enter the number of rows and columns for the 2D array.
o Create a 2D array with the specified dimensions by taking user input.
3. Convert the data into a NumPy array
o Use np.array() to create the 2D array from the list of lists.
4. Input the search element
o Prompt the user to enter the element to search for in the array.
5. Search for the element
o Use np.where() to find the indices of the element in the array.
o If the element is found, np.where() returns a tuple of arrays containing row and column
indices.
o If the element is not found, the indices arrays will be empty.
6. Display the results
o Print the row and column indices of the searched element.
o If the element is not found, display an appropriate message.
7. End

Program

import numpy as np
# Step 1: Input dimensions of the array
rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))

# 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(int, input(f"Row {i+1}: ").split()))
if len(row) != cols:
print(f"Error: Row {i+1} must have exactly {cols} elements.")
exit(1)
array.append(row)
# Convert to NumPy array
array_np = np.array(array)

12
# Step 3: Input the element to search for
search_element = int(input("Enter the element to search for: "))

# Step 4: Use np.where() to search for the element


result = np.where(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, c in zip(result[0], result[1]):
print(f"({r}, {c})")
else:
print(f"Element {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: 7 4 1
Row 2: 8 5 2
Row 3: 9 6 3
Enter the element to search for: 5
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.

13
Ex. No. 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.

Aim:

To write a Python program to create a 2D array and demonstrate aggregation functions sum(),
min(), and max() row-wise and column-wise.

Algorithm:

1. Step 1: Import the required library, numpy, for working with arrays.
2. Step 2: Create a 2D array with predefined values or by accepting user inputs.
3. Step 3: Display the 2D array.
4. Step 4: Calculate and display:
o The sum of each row and column using numpy.sum().
o The minimum value in each row and column using numpy.min().
o The maximum value in each row and column using numpy.max().
5. Step 5: Output the results in a clear format.

Program

import numpy as np

# Step 1: Create a 2D array


array = np.array([[5, 8, 1],
[3, 7, 9],
[4, 6, 2]])

# Step 2: Display the 2D array


print("2D Array:")
print(array)

# Step 3: Row-wise and column-wise aggregation functions


# Row-wise operations
row_sum = np.sum(array, axis=1)
row_min = np.min(array, axis=1)
row_max = np.max(array, axis=1)

# Column-wise operations
col_sum = np.sum(array, axis=0)
col_min = np.min(array, axis=0)
col_max = np.max(array, axis=0)

# Step 4: Display the results


print("\nRow-wise Results:")
print("Sum of rows:", row_sum)
print("Minimum of rows:", row_min)
print("Maximum of rows:", row_max)
14
print("\nColumn-wise Results:")
print("Sum of columns:", col_sum)
print("Minimum of columns:", col_min)
print("Maximum of columns:", col_max)

Output

2D Array:
[[5 8 1]
[3 7 9]
[4 6 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.

15
Ex. No. 9
Write a python program to read a text file and write the content in another file.
Date:

Aim:
To read the content from a text file and write it to another text file using Python.

Algorithm:
1. Open the source file in read mode.
2. Open the destination file in write mode.
3. Read the content of the source file.
4. Write the content to the destination file.
5. Close both the source and destination files.
6. End.

Program

# Open the source file in read mode


source_file = open('source.txt', 'r')

# Open the destination file in write mode


destination_file = open('destination.txt', '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 source.txt to destination.txt.")

Output

#source.txt
Hi,
Welcome to Department of Computer Engineering.
# destination.txt
Hi,
Welcome to Department of Computer Engineering.
Content has been copied successfully from source.txt to destination.txt.

Result:

The program successfully reads the content from source.txt and writes it to destination.txt. It
demonstrates how to open files, read data, and write data in Python.

16
Ex. No. 10
Write a python program to read a csv file using pandas and print the content.
Date:

Aim:

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

# Importing the pandas library


import pandas as pd

# Reading the CSV file into a DataFrame


file_path = 'sample.csv' # Replace with the path to your CSV file
data = pd.read_csv(file_path)

# Printing the content of the CSV file


print(data)

Input

#SAMPLE.CSV

17
Output

S.No REGNO NAME Attendance


0 1 23500949 KATHIRESAN S 40.00
1 2 23500953 LOURDU SAMY A 73.33
2 3 24500975 ANTHONY RUBAN L 6.67
3 4 24500977 ARAVINTH K 86.67
4 5 24500980 ARUNPANDIAN R 93.33
5 6 24500981 ASARATH I 73.33

Result:

The Python program successfully reads the contents of the CSV file using pandas and prints
the data in tabular form.

18

You might also like