0% found this document useful (0 votes)
7 views19 pages

Python Programming Exercises and Solutions

This document contains a series of Python programming exercises aimed at teaching 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 provide practical applications of Python programming for students in the Computer Engineering department at Government Polytechnic College, Villupuram.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views19 pages

Python Programming Exercises and Solutions

This document contains a series of Python programming exercises aimed at teaching 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 provide practical applications of Python programming for students in the Computer Engineering department at Government Polytechnic College, Villupuram.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

128–GOVERNMENTPOLYTECHNICCOLLEGE

Arakandanallur,VillupuramDistrict.

DepartmentofComputerEngineering

1052234440-PYTHONPROGRAMMING (2023

REGULATION)
IIYear /IVthSemester

Prepared
By,[Link],M.
E., Lecturer,
DepartmentofComputerEngineering,
128–GovernmentPolytechnicCollege,
Villupuram.

1
[Link].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:
oPrompt 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:

#Programtofindthegreatestofthreenumbers

#Input:Readingthreenumbersfromtheuser
a=float(input("Enterthefirstnumber:"))
b=float(input("Enterthesecondnumber:"))
c=float(input("Enterthethirdnumber:"))

#Logic:Findingthegreatestnumber if a
>= b and a >= c:
greatest=a
elifb>=aandb>=c: greatest =
b
else:
greatest=c

#Output:Displaythegreatestnumber
print(f"Thegreatestnumberamong{a},{b},and{c}is{greatest}.")

2
Output:

Enter the first number: 25


Enterthesecondnumber:41
Enter the third number: 20
Thegreatestnumberamong25.0,41.0,and20.0is41.0.

Result:
ThePythonprogramsuccessfullyusesvariablesa,b,andctoreadthreenumbers,comparesthem,and prints the
greatest among the three numbers.

3
[Link].2 WriteapythonprogramtofindthesumofNnumberusingrange()functioninfor loop.
Date:

Aim

TowriteaPythonprogramtocalculatethesumofthefirstNnaturalnumbersusingtherange() function in
a for loop.

Algorithm

1. Start
2. Input:Prompttheusertoenterapositiveinteger N.
3. Initialize:Setavariabletotal_sumto0.
4. Loop:Useaforloopwiththerange()functiontoiterateovernumbersfrom1toN(inclusive).
o Add:Addthecurrentnumbertototal_sumduringeachiteration.
5. Output:Aftertheloopends,printthesumofthefirstNnaturalnumbers.
6. End

Program:

#ProgramtofindthesumofthefirstNnaturalnumbersusingrange()inaforloop

#Step1: Input
N=int(input("EnterapositiveintegerN:"))

#Step2:Initialize
total_sum = 0

#Step3:LoopandAdd for
number in range(1, N + 1):
total_sum+=number

#Step4:Output
print(f"Thesumofthefirst{N}naturalnumbersis: {total_sum}")

Output:

EnterapositiveintegerN:5
Thesumofthefirst5naturalnumbersis:15

Result:
The Python program successfully calculates the sum of the first N natural numbers using the
range()[Link].

4
[Link].3 Writeapythonprogramtodemonstratethestringslicing,concatenation,replication and
Date: len() method.

Aim

TowriteaPythonprogramtodemonstratestringslicing,concatenation,replication,andthelen() method.

Algorithm

1. Start
2. Defineastring,str1,fordemonstrationpurposes(e.g.,"Hello,World!").
3. StringSlicing:
o Useslicingtechniquestoextractpartsofthestring,suchasstr1[0:5]forthefirst5
characters.
4. StringConcatenation:
o Defineanotherstring,str2(e.g.,"WelcometoPython!"),andconcatenateitwithstr1 using
the + operator.
5. StringReplication:
o Replicatethestringstr1multipletimesusingthe*operator.
6. Usinglen()Method:
o Usethelen()methodtocalculateandprintthelengthofstr1.
7. Displayalloutputstotheuser.
8. End

Program

#Demonstrationofstringslicing,concatenation,replication,andlen()method

#Step1:Definethestring str1
= "Hello, World!"

#Step2:StringSlicing
sliced_part=str1[0:5] #First5characters
sliced_part_2=str1[7:] #From7thcharactertoend

#Step3:StringConcatenation str2
= " Welcome to Python!"
concatenated_string = str1 + str2

# Step 4: String Replication


replicated_string=str1*3#Replicate3times

#Step5:Usinglen()Method
length_of_string = len(str1)

5
# Output results
print("Original String:", str1)
print("SlicedPart(0-5):",sliced_part)
print("Sliced Part (7 to end):", sliced_part_2)
print("Concatenated String:", concatenated_string)
print("ReplicatedString(3times):",replicated_string)
print("Length of Original String:", length_of_string)

Output
OriginalString:Hello,World!
Sliced Part (0-5): Hello
SlicedPart(7toend):World!
ConcatenatedString:Hello,World!WelcometoPython!
ReplicatedString(3times):Hello,World!Hello,World!Hello,World!
Length of Original String: 13

Result:
ThePythonprogramsuccessfullydemonstratestheusageofstringslicing,concatenation, replication,
and the len() method, providing expected outputs.

6
[Link].4 Write a python program to create a tuple and convert into a list and print
Date: thelist in sorted order.

Aim

TowriteaPythonprogramtocreateatuple,convertitintoalist,andprintthelistinsorted
order.

Algorithm

1. Start
2. Createatuplewithsomeelements.
3. Convertthetupleintoalistusingthelist()function.
4. Usethesorted()functiontosortthelistinascendingorder.
5. Printtheoriginaltuple,theconvertedlist,andthesortedlist.
6. End

Program
#Step1:Createatuple
my_tuple=(23,1,45,12,8,19)

#Step2:Convertthetupleintoalist
my_list = list(my_tuple)

#Step3:Sortthelist sorted_list
= sorted(my_list)

#Step4:Printtheresults
print("Original Tuple:", my_tuple)
print("Converted List:", my_list)
print("Sorted List:", sorted_list)

Output:
OriginalTuple:(23,1,45,12,8, 19)
ConvertedList:[23,1,45,12,8, 19]
SortedList:[1,8,12,19,23, 45]

Result:
ThePythonprogramsuccessfullycreatesatuple,convertsitintoalist,andprintsthelistin sorted order.

7
[Link].5 Writeapythonprogramtocreateadictionaryandcheckwhetherakeyor value exist
Date: in the dictionary.

Aim

TowriteaPythonprogramthatcreates adictionaryand checkswhetherakeyorvalue existsin the


dictionary.

Algorithm

1. Start
2. Createanemptydictionaryorinitializeitwithsomepredefinedkey-valuepairs.
3. Prompttheusertoinputkey-valuepairsandupdatethedictionary(optional).
4. Displaythedictionaryto theuser.
5. Prompttheuserto inputakeytocheckifitexistsinthedictionary:
o Ifthekeyexists,print"Keyexistsinthedictionary".
o Otherwise,print"Keydoesnotexistinthedictionary".
6. Prompttheusertoinputavaluetocheckifitexistsinthedictionary:
o Ifthevalueexists,print"Valueexistsinthedictionary".
o Otherwise,print"Valuedoesnotexistinthedictionary".
7. End

Program

#Step1:Initializethedictionary
my_dict={"name":"Alice","age":"25","city":"NewYork"}

#Step2:Displaythedictionary
print("Dictionary:", my_dict)

# Step 3: Check if a key exists


key_to_check=input("Enterakeytocheck:") if
key_to_check in my_dict:
print(f"Key'{key_to_check}'existsinthedictionary.") else:
print(f"Key'{key_to_check}'doesnotexistinthedictionary.")

# Step 4: Check if a value exists


value_to_check=input("Enteravaluetocheck:") if
value_to_check in my_dict.values():
print(f"Value'{value_to_check}'existsinthedictionary.")

8
else:
print(f"Value'{value_to_check}'doesnotexistinthedictionary.")
Output:

Dictionary:{'name':'Alice','age':'25','city':'NewYork'} Enter a
key to check: name
Key'name'existsinthedictionary.
Enter a value to check: 25
Value'25'existsinthedictionary.

Result:

Theprogramsuccessfullycreatesadictionary,checksfortheexistenceofakeyorvalue,and provides
accurate results.

9
[Link].6 Write a python program to create one dimensional array and convert into a2D-
Date: dimensional array using reshape(), print the first two columns alone using
slicing.

Aim

TowriteaPythonprogramtocreate aone-dimensionalarray,convertitintoatwo-dimensionalarray using the


reshape() method, and print the first two columns alone using slicing.

Algorithm

1. Step1:Importtherequiredlibrary.
o Importthenumpylibraryforarraymanipulation.
2. Step2:Createaone-dimensionalarray.
o [Link]()tocreateaone-dimensionalarraywithsomesampleelements.
3. Step3:Reshapetheone-dimensionalarrayintoatwo-dimensionalarray.
o Usethereshape()function toreshapethearrayintoa2Darraywiththedesirednumber of rows
and columns.
4. Step4:Printthetwo-dimensionalarray.
o Displaythereshaped2Darrayforverification.
5. Step5:Sliceandprintthefirsttwocolumns.
o Useslicing([:,:2])toextractthefirsttwocolumnsofthe2Darrayandprintthem.
6. Step6:Displaytheoutputandconcludetheprogram.

Program

importnumpyasnp

# Step 1: Create a one-dimensional array


one_d_array=[Link]([1,2,3,4,5,6,7,8,9,10,11,12])

#Step2:Reshapethearrayintoatwo-dimensionalarray(4rows,3columns) two_d_array =
one_d_array.reshape(4, 3)

#Step3:Printthe2Darray
print("Two-dimensional array:")
print(two_d_array)

#Step4:Printthefirsttwocolumnsofthe2Darray print("\
nFirst two columns:")
print(two_d_array[:,:2])

10
Output

Two-dimensionalarray:
[[ 123]
[ 456]
[ 789]
[101112]]

Firsttwocolumns: [[
12]
[ 45]
[ 78]
[10 11]]

Result:

Theprogramsuccessfullycreatesaone-dimensionalarray,convertsitintoatwo-dimensional array
using the reshape() method, and prints the first two columns using slicing.

11
[Link].7 Writeapythonprogramtocreatetwo-dimensionalarrayandsearchforan element
Date: using where () function.

Aim

TowriteaPythonprogramtocreate atwo-dimensionalarrayandsearchforanelementusing the


where() function from the NumPy library.

Algorithm

1. Start
o ImporttheNumPylibraryasnp.
2. Inputthearraydimensionsandelements
o Prompttheusertoenterthenumberofrowsandcolumnsforthe2Darray.
o Createa2Darraywiththespecifieddimensionsbytakinguserinput.
3. ConvertthedataintoaNumPyarray
o [Link]()tocreatethe2Darrayfromthelistoflists.
4. Inputthesearchelement
o Prompttheusertoentertheelementtosearchforinthearray.
5. Searchfortheelement
o [Link]()tofindtheindicesoftheelementinthearray.
o Iftheelementisfound,[Link]()returnsatupleofarrayscontainingrowandcolumn indices.
o Iftheelementisnotfound,theindicesarrayswillbeempty.
6. Displaytheresults
o Printtherowandcolumnindicesofthesearchedelement.
o Iftheelementisnotfound,displayanappropriatemessage.
7. End

Program

importnumpyasnp
#Step1:Inputdimensionsofthearray rows =
int(input("Enter the number of rows: "))
cols=int(input("Enterthenumberofcolumns:"))

#Step2:Inputelementstocreatea2Darray
print("Enter the elements row by row:")
array=[]
fori inrange(rows):
row=list(map(int,input(f"Row{i+1}:").split())) if
len(row) != cols:
print(f"Error:Row{i+1}musthaveexactly{cols}elements.")
exit(1)
[Link](row)
#ConverttoNumPyarray
array_np = [Link](array)

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

#Step4:[Link]()tosearchfortheelement result =
[Link](array_np == search_element)

#Step5:Displaytheresults if
result[0].size > 0:
print(f"Element{search_element}foundatthefollowingpositions(row,column):") for r,
c in zip(result[0], result[1]):
print(f"({r},{c})")
else:
print(f"Element{search_element}notfoundinthearray.")

Output

Enter the number of rows: 3


Enterthenumberofcolumns:3
Entertheelementsrowbyrow:
Row1:741
Row2:852
Row3:963
Entertheelementtosearchfor:5
Element5foundatthefollowingpositions(row,column):(1,1)

Result:

Theprogramsuccessfullycreatesatwo-dimensionalarray,searchesforaspecifiedelement using the


where() function, and displays the positions of the element if found.

13
[Link].8 Writeapythonprogramtocreatea2D-dimensionalarrayanddemonstrate
Date: aggregationfunctionssum(),min()andmax()intherowandcolumnwise.

Aim:

TowriteaPythonprogramtocreate a2Darrayanddemonstrateaggregationfunctionssum(), min(), and


max() row-wise and column-wise.

Algorithm:

1. Step1:Importtherequiredlibrary,numpy,forworkingwitharrays.
2. Step2:Createa2Darraywithpredefinedvaluesorbyacceptinguserinputs.
3. Step3:Displaythe2Darray.
4. Step4:Calculateanddisplay:
o [Link]().
o [Link]().
o [Link]().
5. Step5:Outputtheresultsinaclearformat.

Program

importnumpyasnp

#Step1:Createa2Darray array
= [Link]([[5, 8, 1],
[3,7,9],
[4,6,2]])

#Step2:Displaythe2Darray
print("2D Array:")
print(array)

#Step3:Row-wiseandcolumn-wiseaggregationfunctions #
Row-wise operations
row_sum=[Link](array,axis=1)
row_min = [Link](array, axis=1)
row_max=[Link](array,axis=1)

#Column-wiseoperations
col_sum = [Link](array, axis=0)
col_min = [Link](array, axis=0)
col_max = [Link](array, axis=0)

#Step4:Displaytheresults
print("\nRow-wise Results:")
print("Sum of rows:", row_sum)
print("Minimum of rows:", row_min)
print("Maximumofrows:",row_max)

14
15
print("\nColumn-wise Results:")
print("Sum of columns:", col_sum)
print("Minimum of columns:", col_min)
print("Maximumofcolumns:",col_max)

Output

2DArray:
[[581]
[379]
[462]]

Row-wiseResults:
Sumofrows:[141912]
Minimumofrows:[13 2]
Maximumofrows:[896]

Column-wiseResults:
Sumofcolumns:[122112]
Minimumofcolumns:[36 1]
Maximumofcolumns:[589]

Result:

ThePythonprogramsuccessfullycreateda2Darrayanddemonstratedtheuseofaggregation functions
sum(), min(), and max() row-wise and column-wise.

16
[Link].9
Date: Writeapythonprogramtoreadatextfileandwritethecontentinanotherfile.

Aim:
Toreadthecontentfrom atextfileandwriteittoanothertextfileusingPython.

Algorithm:
1. Openthe sourcefileinreadmode.
2. Openthe destinationfileinwrite mode.
3. Readthecontentofthesourcefile.
4. Writethecontent tothedestinationfile.
5. Closeboththesourceanddestinationfiles.
6. End.

Program

#Openthesourcefileinreadmode
source_file = open('[Link]', 'r')

#Openthedestinationfileinwritemode
destination_file = open('[Link]', 'w')

#Readcontentfromsourcefile content
= source_file.read()

#Writecontenttodestinationfile
destination_file.write(content)

#Closebothfiles
source_file.close()
destination_file.close()

print("[Link].")

Output

#[Link]
Hi,
WelcometoDepartmentofComputerEngineering.
#[Link]
Hi,
WelcometoDepartmentofComputerEngineering.
[Link].

Result:

The program successfully reads the content from [Link] and writes it to [Link].
Itdemonstrates how to open files, read data, and write data in Python.

17
[Link].10
Date: Writeapythonprogramtoreadacsvfileusingpandasandprintthecontent.

Aim:

ToreadanddisplaythecontentsofaCSVfileusingthepandaslibraryin Python.

Algorithm:

1. Importpandas:Importthepandaslibrary,whichprovidesfunctionstohandledatainCSV format.
2. Read theCSVFile:Usetheread_csv()functionfrompandastoreadtheCSVfileintoa
DataFrame.
3. DisplaytheContent:PrintthecontentoftheDataFrameusingtheprint()function.

Program

#Importingthepandaslibrary
import pandas as pd

#ReadingtheCSVfileintoaDataFrame
file_path='[Link]'#ReplacewiththepathtoyourCSVfile data =
pd.read_csv(file_path)

#PrintingthecontentoftheCSVfile
print(data)

Input

#[Link]

18
Output

[Link] REGNO NAME Attendance


0 1 23500949 KATHIRESANS 40.00
1 2 23500953 LOURDUSAMY A 73.33
2 3 24500975 ANTHONYRUBANL 6.67
3 4 24500977 ARAVINTHK 86.67
4 5 24500980 ARUNPANDIAN R 93.33
5 6 24500981 ASARATHI 73.33

Result:

The Python program successfully reads the contents of the CSV file usingpandasand printsthe
data in tabular form.

19

You might also like