Problem Solving and Python Programming

MahaJeya 2,033 views 145 slides Feb 22, 2022
Slide 1
Slide 1 of 145
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145

About This Presentation

GE8151-PSPP


Slide Content

KARPAGAM INSTITUTE OF TECHNOLOGY,
COIMBATORE -105
Course Code with Name: GE8151 -Problem Solving and Python Programming
Staff Name / Designation: A.Mahalakshmi / Assistant Professor
Department : Information Technology
Year / Semester : I / I
Department of Information Technology

UNIT I -ALGORITHMIC PROBLEM SOLVING
SYLLABUS:
Algorithms, building blocks of algorithms (statements, state,
control flow, functions), notation(pseudo code, flow chart,
programming language), algorithmic problem solving,
simple strategiesfordeveloping algorithms (iteration,
recursion).
Illustrativeproblems: find minimum in a list, insert acardin
a list of sorted cards, guess an integer number in a range,
Towers of Hanoi.
2/22/2022 Karpagam Insitute of Technology 22/22/2022 2

ALGORITHMS
•Step-by-step procedure to solve a problem.
2/22/2022 3Karpagam Institute of Technology

CHARACTERISTICS OF AN ALGORITHM
•The instructions should be in a ordered manner.
•The instructions must be simple and concise.
•They must not be ambiguous.
•The algorithm must completely and definitely
solve the problem.
2/22/2022 4Karpagam Institute of Technology

ADVANTAGES OF ALGORITHM
Easy to understand.
Programs can be easily developed.
2/22/2022 5Karpagam Institute of Technology

Write the algorithm to find the sum and average of
given 2 numbers.
Step1 : Start
Step2 : Read values of A and B
Step3 : Calculate SUM =A+B
Step4 : Calculate AVERAGE = (SUM/2)
Step5 : Print Values of SUM and AVERAGE
Step6 : Stop
2/22/2022 6Karpagam Institute of Technology

BUILDING BLOCKS OF ALGORITHMS
Statement
State
Control Flow
Functions
2/22/2022 7Karpagam Institute of Technology

STATEMENT
•Statement is a single action in a computer.
•In a computer statements might include some of
the following actions,
Input data-information given to the program
Process data-perform operation on a given input
Output data-processed result
2/22/2022 8Karpagam Institute of Technology

STATE
•Transition from one process to another process
under specified condition within a time is
called state.
2/22/2022 9Karpagam Institute of Technology

CONTROL FLOW
•Theprocessofexecutingtheindividual
statementsinagivenorderiscalledcontrol
flow.
•Thecontrolcanbeexecutedinthreeways
Sequence
Selection
Iteration
2/22/2022 10Karpagam Institute of Technology

SEQUENCE
•Alltheinstructionsareexecutedoneafteranother
iscalledsequenceexecution.
•Example:Sumoftwonumbers:
Step1:Start
Step2:Readthevaluesofaandb
Step3:calculatec=a+b
Step4:Displayc
Step5:Stop
2/22/2022 11Karpagam Institute of Technology

SELECTION
•Selectionexecutionisbaseduponthecondition.
•Iftheconditionaltestistrue,onepartofthe
programwillbeexecuted.
•Otherwise,itwillexecutetheotherpartofthe
program.
2/22/2022 12Karpagam Institute of Technology

Write an algorithm to check whether he is
eligible to vote?
Step 1: Start
Step 2: Get age
Step 3: if age >= 18 print “Eligible to vote”
Step 4: else print “Not eligible to vote”
Step 6: Stop
2/22/2022 13Karpagam Institute of Technology

ITERATION
•Setofstatementsareexecutedagainandagainbasedupon
conditionaltest.
•Writeanalgorithmtoprintall‘n’naturalnumbers
Step1:Start
Step2:getnvalue.
Step3:initializei=1
Step4:if(i<=n)gotostep5elsegotostep7
Step5:Printivalueandincrementivalueby1
Step6:gotostep4
Step7:Stop
2/22/2022 14Karpagam Institute of Technology

FUNCTIONS
•Functionisasubprogramwhichconsistsofblockofcode(setof
instructions)thatperformsaparticulartask.
•Algorithmforadditionoftwonumbersusingfunction
Mainfunction
Step1:Start
Step2:Callthefunctionadd()
Step3:Stop
Subfunction
Step1:Functionstart
Step2:Geta,bValues
Step3:addc=a+b
Step4:Printc
Step5:Return
2/22/2022 15Karpagam Institute of Technology

FLOW CHART
•Pictorialrepresentationofanalgorithm.
•Sinceitisavisualrepresentation,ithelpstounderstandthelogicof
theprogram.
2/22/2022 16Karpagam Institute of Technology

Draw a flowchart to find the sum and average
of given two numbers.
2/22/2022 17Karpagam Institute of Technology

Draw a flowchart to find the smallest of given
two numbers.
2/22/2022 18Karpagam Institute of Technology

PSEUDOCODE
•Pseudocodeonlydescribesthelogictodevelopaprogram
anditcanbetranslatedtoanycomputerlanguagecode.
•Keywordsshouldbehighlightedbycapitalizingthem.
•UsingKeywords:
Input:READ,OBTAIN,GET
Output:PRINT,DISPLAY,SHOW
Compute:COMPUTE,CALCULATE,DETERMINE
Initialize:SET,INITIALIZE
Addone:INCREMENT,BUMP
2/22/2022 19Karpagam Institute of Technology

Write a pseudo code to accept two numbers from the
keyboard and calculate the sum and
product of them, also display the result on the
monitor screen.
BEGIN
READ A, B
CALCUALTE Sum=A+B
DISPLAY Sum
END
2/22/2022 20Karpagam Institute of Technology

PROGRAMMING LANGUAGE
•Computerprogramminglanguagesareusedtocommunicate
instructionstoacomputer.
InterpretedProgrammingLanguages
FunctionalProgrammingLanguages
CompiledProgrammingLanguages
ProceduralProgrammingLanguages
ScriptingProgrammingLanguages
MarkupProgrammingLanguages
Logic-BasedProgrammingLanguages
ConcurrentProgrammingLanguages
Object-OrientedProgrammingLanguages
2/22/2022 21Karpagam Institute of Technology

PROGRAMMING LANGUAGE CONTD..
InterpretedProgrammingLanguages
•Aninterpretedlanguageexecuteinstructions
directly,withoutpreviouslycompilinga
programintomachine-languageinstructions.
•Examples:APL,BASIC,ICI,J,Lisp,Lua,M,
Pascal,Perl,Python,Ruby,S-Lang,spin
2/22/2022 22Karpagam Institute of Technology

PROGRAMMING LANGUAGE CONTD..
FunctionalProgrammingLanguage:
•Theyfocusontheapplicationoffunctions.
•Manyfunctionalprogramminglanguagesarebound
tomathematicalcalculations.
Examples:-
•ML,Joy,Kite,Clean,OPAL,Q
2/22/2022 23Karpagam Institute of Technology

PROGRAMMING LANGUAGE CONTD..
CompiledProgrammingLanguages
•Acompiledlanguageisaprogramming
languagewhoseimplementationsaretypically
compilers.
•Examples:Ada,ALGOL,C,C++,C#,
COBOL,etc.
2/22/2022 24Karpagam Institute of Technology

PROGRAMMING LANGUAGE CONTD..
ProceduralProgrammingLanguages
•Procedural(imperative)programmingimplies
specifyingthestepsthattheprogramsshould
taketoreachtoanintendedstate.
•Examples:Bliss,ChucK,CLIST,HyperTalk,
Modula-2,Oberon,Component,Pascal,
MATLAB,PL/C,PL/I,Rapira,RPG
2/22/2022 25Karpagam Institute of Technology

PROGRAMMING LANGUAGE CONTD..
ScriptingLanguages
•Scriptinglanguagesareprogramming
languagesthatcontrolanapplication.
•Examples: AppleScript,BeanShell,
ColdFusion,F-Script,JASS,PHP,VBScript,
WindowsPowerShell
2/22/2022 26Karpagam Institute of Technology

PROGRAMMING LANGUAGE CONTD..
MarkupLanguages
•Amarkuplanguageisanartificiallanguage
thatusesannotationstotextthatdefinehow
thetextistobedisplayed.
•Examples:Curl,SGML,HTML,XML,
XHTML
2/22/2022 27Karpagam Institute of Technology

PROGRAMMING LANGUAGE CONTD..
Logic-basedProgrammingLanguages
•Logicprogrammingisatypeofprogramming
paradigmwhichislargelybasedonformal
logic.
•Examples:ALF,Fril,Janus,Oz,Poplog,
Prolog,ROOP
2/22/2022 28Karpagam Institute of Technology

PROGRAMMING LANGUAGE CONTD..
ConcurrentProgrammingLanguages:
•Itisacomputerprogrammingtechnique,which
executestheoperationconcurrently–eitherwithin
singlecomputeroracrossnumberofsystems.
Examples:
•ABCL,ConcurrentPascal,E,Joule,SALSA,Pict,
SR,etc.
2/22/2022 29Karpagam Institute of Technology

PROGRAMMING LANGUAGE CONTD..
Object-OrientedProgrammingLanguages
•Object-orientedprogramming(OOP)isa
programmingparadigmbasedontheconceptof
“objects”,whichmaycontaindata,intheformof
fields,oftenknownasattributes;andcode,inthe
formofprocedures,oftenknownasmethods.
•Examples:IO,Slate,Self,Scala,Prograph,
Oxygene,Moto,MOO,Lava,BETA,Agora
2/22/2022 30Karpagam Institute of Technology

ALGORITHMIC PROBLEM SOLVING
➢Understandingtheproblem
➢Ascertainthecapabilitiesofthecomputational
device
➢Exact/approximatesolution
➢Decideontheappropriatedatastructure
➢Algorithmdesigntechniques
➢Methodsofspecifyinganalgorithm
➢Provinganalgorithmscorrectness
➢Analyzinganalgorithm
2/22/2022 31Karpagam Institute of Technology

UNDERSTANDING THE PROBLEM
•The problem given should be clearly and
completely understood.
2/22/2022 32Karpagam Institute of Technology

DETERMINING THE CAPABILITIES OF
THE COMPUTATIONAL DEVICE
•After understanding the problem, speed and
memory availability of the device are to be
noted.
2/22/2022 33Karpagam Institute of Technology

EXACT /APPROXIMATE SOLUTION
•Oncealgorithmisdevised,itisnecessarytoshowthat
howitcomputesanswerforallthepossiblelegal
inputs.
•ExamplesofExactsolutionproblemsare
i)Computingadditionof2numbers.
ii)Findthegivennumberisprimeornot.
ExamplesofApproximatesolutionproblemswherean
exactsolutioncannotbeobtainedare
i)Findingasquarerootofnumber.
ii)Solutionsofnonlinearequations.
2/22/2022 34Karpagam Institute of Technology

DECIDE ON THE APPROPRIATE DATA
STRUCTURE
•Datatypeisawelldefinedcollectionofdatawiththewell
definedsetofoperationsonit.
•Adatastructureisbasicallyagroupofdataelements.
•TheElementarydatastructuresareasfollows,
List:Allowsfastaccessofdata
Sets:Treatdataaselementofaset.Allowsapplicationof
operationssuchasintersection,Unionandequivalence.
Dictionaries:Allowsdatatobestoredasakeyvaluepair.
2/22/2022 35Karpagam Institute of Technology

ALGORITHM DESIGN TECHNIQUES
•Creatinganalgorithmisanart.
•Bymasteringthesedesignstrategies,itwill
becomeeasiertodevisenewanduseful
algorithms.
2/22/2022 36Karpagam Institute of Technology

METHODS OF SPECIFYING AN
ALGORITHM
•Use of natural language or pseudocode.
•Flow Chart
2/22/2022 37Karpagam Institute of Technology

PROVING AN ALGORITHMS
CORRECTNESS
•Itisnecessarytoprovethatalgorithm
computessolutionsforallthepossiblevalid
input.
2/22/2022 38Karpagam Institute of Technology

ANALYZING THE PERFORMANCE OF
ALGORITHMS
•Analgorithmisanalyzedtomeasureits
performanceintermsofCPUtimeandmemory
spacerequiredtoexecutethatalgorithm.
2/22/2022 39Karpagam Institute of Technology

SIMPLE STRATEGIES FOR DEVELOPING
ALGORITHMS (ITERATION,
RECURSION)
ITERATION
•ALoopisoneormoreinstructionsthatthecomputer
performsrepeatedly.
•Algorithm:Writethealgorithmtoprint“1to5”
Step1:Start
Step2:Initializethevalueofias1
Step3:Printiandincrementthevalueofi
Step4:RepeattheStep3untilthevalueofi<=5.
Step5:Stop
2/22/2022 40Karpagam Institute of Technology

RECURSION
•Afunctionthatcallsitselfisknownasrecursivefunctionandthe
phenomenoniscalledasrecursion.
•Algorithm:Writeanalgorithmtofindthefactorialofagiven
number
MainProgram:
Step1:Start
Step2:Readn
Step3:Callthesubprogramasf=fact(n)
Step4:printfvalue
Step5:Stop
SubProgram:
Step1:Ifn==0orn==1return1tothemainprogramotherwisegoto
step2
Step2:returnn*fact(n-1)tomainprogram
2/22/2022 41Karpagam Institute of Technology

FINDING MINIMUM IN A LIST
Step1:Start
Step2:ReadthelistofnumbersasL
Step3:SetMintolist[0]
Step4:ForeachnumberxinthelistL,compareit
tomin
Step4a:Ifxissmaller,thenassignmintox
Step5:Printmin
Step6:Stop
2/22/2022 42Karpagam Institute of Technology

GUESS AN INTEGER NUMBER IN A
RANGE
Step1:Start
Step2:Generatearandomnumberinbetween1and100
Step3:Gettheguessednumberfromtheuser
Step4:Iftherandomnumberisequaltotheguessednumber
printguessingiscorrect.
Step5:OtherwiseIftherandomnumberisgreaterthanthe
guessednumberprintguessingistoohighandgoto
step7
Step6:Otherwiseprintguessingistoohighandgotostep7.
Step7:Stop
2/22/2022 43Karpagam Institute of Technology

INSERT A CARD IN A LIST OF SORTED
CARDS
Step1-Start
Step2-Readthelistofsortedcards.
Step3-Ifitisthefirstcard,itisalreadysorted.return1;
Step4-Picknextcard
Step5-Comparewithallcardsinthesortedsub-list
Step6-Shiftallthecardsinthesortedsub-listthatis
greaterthanthevalueofthecardtobeinserted.
Step5-Insertthecard
Step6-Repeatuntillistissorted.
Step7-Stop
2/22/2022 44Karpagam Institute of Technology

TOWERS OF HANOI
•Problem:
•TowerofHanoiisamathematicalpuzzlewith
threerodsand‘n’numberofdisks.
•Thesedisksareindifferentsizesandstacked
uponinanascendingorder,i.ethesmallerone
sitsoverthelargerone.
•Theobjectiveistomoveallthediskstosome
anothertowerwithoutviolatingthesequence
ofarrangement.
2/22/2022 45Karpagam Institute of Technology

RULES TO BE FOLLOWED
•Only one disk can be moved among the towers
at any given time.
•Only the “top” disk can be removed.
•No large disk can sit over a small disk.
2/22/2022 46Karpagam Institute of Technology

2/22/2022 47Karpagam Institute of Technology

VIDEO TUTORIAL
S.NO TOPIC LINK
1 Minimuminalist https://youtu.be/5Y1rxCMY_jU
2 InsertaCardinalistof
SortedCards
https://youtu.be/Mow8rdOKrbY
3 Guessanintegernumber
inarange
https://youtu.be/pmDKRJdqT1E
4 TowerofHanoni https://youtu.be/hKUwLe7bpwo
2/22/2022 48Karpagam Institute of Technology

SUMMARY OF UNIT I
•Algorithm, Flow chart, Pseudo code
•Building Blocks of an Algorithm
•Algorithmic Problem Solving Technique
•Simple Strategies for developing an algorithm
•Illustrative Problems for developing an algorithms
2/22/2022 Karpagam Insitute of Technology 492/22/2022 49

ASSIGNMENT QUESTION S
S.NO QUESTIONS BLOOMS LEVEL
1 Applytherulesofanalgorithmand
pseudocodetofindwhetherthegiven
numberispositive,negativeandzero.
K3
2 Applytherulesofanalgorithmand
pseudocodetofindthefactorialofagiven
numberusingrecursion.
K3
3 Writeapseudocodeforconvertingcelsius
ofagivenvalueintofahrenheit.
K3
4 Developaflowchartforperforming
TowersofHanoioperation.
K5
5 Designaflowchartforcalculatingsimple
interest
K5
2/22/2022 50Karpagam Institute of Technology

QUIZ-TEST YOUR KNOWLEDGE
•https://docs.google.com/forms/d/e/1FAIpQLSe
crZ0M-AnDkGI5HOSpzjHrHiDacakocv_-u2K
s_zul55YF0w/viewform
2/22/2022 Karpagam Insitute of Technology 512/22/2022 51

UNIT II DATA, EXPRESSIONS, STATEMENTS
SYLLABUS:
Pythoninterpreterandinteractivemode;valuesandtypes:int,
float,boolean,string,andlist;variables,expressions,statements,
Tupleassignment,precedenceofoperators,comments;modules
andfunctions,functiondefinitionanduse,flowofexecution,
parametersandarguments;
Illustrativeprograms:exchangethevaluesoftwovariables,
circulatethevaluesofnvariables,distancebetweentwopoints.
2/22/2022 522/22/2022 52Karpagam Institute of Technology

PYTHON INTERPRETER AND INTERACTIVE MODE
INTERACTIVE MODE PROGRAMMING:
•Interactivemodeisacommandlineshellwhichgives
immediatefeedbackforeachstatement.
•Inthismode,thepromptsforthenextcommandusuallyhave
threegreater-thansigns(>>>).
•Example-A sample interactive session:
>>> 5
5
>>> print(5*7)
35
>>> "hello" * 4
'hellohellohellohello'
2/22/2022 53Karpagam Institute of Technology

PYTHON INTERPRETER AND INTERACTIVE MODE
CONTD..
SCRIPT/INTERPRETER MODE PROGRAMMING
•In script mode, execution of the script begins and continues
until the script is finished.
•Example:
2/22/2022 54Karpagam Institute of Technology

VALUES AND TYPES
•VALUE–refers to the basic things in a program works which
can be like a letter or a number.
•TYPE-refers to the data type, which is used to find the type
of data.
Following are the various basic types of a value:
2/22/2022 55Karpagam Institute of Technology
S.NO TYPES EXAMPLE OF VALUES
1 Int 10,100,-256,789656
2 Float 3.14,2.56789,-21.9
3 Boolean True or False
4 String “Hai” or ‘Hi’
5 List [0,1,2,3,4]
6 Tuple (0,1,2,3,4)
7 Dictionaries {1:“Hai”, 2: “Welcome”}

VALUES AND TYPES CONTD..
•INTEGER-it is represented by a whole number.
>>>type(3)
<type ‘int’>
•FLOAT-Numbers with a decimal point
>>>type(3.2)
<type 'float'>
•BOOLEAN-it is represented by TRUE or FALSE
>>> bool(1)
True
>>> bool(0)
False
>>>type(2>3)
<class ‘bool’>
2/22/2022 56Karpagam Institute of Technology

VALUES AND TYPES CONTD..
•STRING -values with quotes like single, double, triple
>>>type('17')
<type 'str'>
•LIST-collection of elements in square bracket [ ]
>>>a=[1,2,3]
>>>type(a)
<tupe‘list’>
•TUPLE -collection of elements in paranthesis( )
>>>a=(1,2,3)
>>>type(a)
<type ‘tuple’>
•DICTIONARY–Collectionofelementsincurlybraces{}withkey:value
pair
>>>a={1: “hai”, 2: “welcome”}
>>>type(a)
<type ‘dict’>
2/22/2022 57Karpagam Institute of Technology

VARIABLES
•Variables are defined as reserved memory locations to store
values.
Rules for Naming Variables
•Variable names can contain letters, symbols like underscore
(__) and numbers.
•They begin with a letter not numbers.
•Both uppercase and lowercase letters are used.
•Keywords cannot be used as variable names.
•Example for valid identifier
•abc, xy12, good_start
•Example for non-valid identifier
•12xy, x$y
2/22/2022 58Karpagam Institute of Technology

EXPRESSIONS
•Anexpressionisacombinationofvalues,variables,
andoperators.
•Examples:
–17
–x
–x+17
2/22/2022 59Karpagam Institute of Technology

STATEMENTS
•Eachandeveryinstructionorlineintheprogramis
calledasstatements.
•Example:
A=10 #assignmentstatement
B=20 #assignmentstatement
C=A+B #assignmentstatement
print(C) #printstatement
Output:
30 #outputstatement
2/22/2022 60Karpagam Institute of Technology

TUPLE ASSIGNMENT
•Python has a very powerfultuple assignmentfeature that
allows a tuple of variables on the left of an assignment to be
assigned values from a tuple on the right of the assignment.
•For example, to swapaandb:
a=10
b=20
temp = a
a = b
b = temp
•Tuple assignment solves this problem neatly:
(a,b) = (b,a)
2/22/2022 61Karpagam Institute of Technology

PRECEDENCE OF OPERATORS
ORDER OF OPERATIONS:
•When more than one operator appears in an expression, the
order of evaluation depends on the rules of precedence.
•The acronym PEMDAS is a useful way to remember the rules:
–Parentheses have the highest precedence
•2 * (3-1) is 4, and
•(1+1)**(5-2) is 8.
-Exponentiation has the next highest precedence
•2**1+1 is 3, not 4, and
•3*1**3 is 3, not 27.
2/22/2022 62Karpagam Institute of Technology

PRECEDENCE OF OPERATORS CONTD..
•Multiplication and Division have the same precedence, which
is higher than Addition and Subtraction, which also have the
same precedence.
–2*3-1 is 5, not4, and
–6+4/2 is 8, not 5.
•Operators with the same precedence are evaluated from left to
right (except exponentiation).
–So in the expression degrees / 2 * pi, the division happens
first andthe result is multiplied by pi.
2/22/2022 63Karpagam Institute of Technology

PRECEDENCE OF OPERATORS CONTD..
Operator Description
** Exponentiationraise to the power
~ ,+,- Complement, unary plus and minus
*, /,%, // Multiply, divide, modulo and floor division
+, - Addition and subtraction
>> , << Right and left bitwise shift
& Bitwise 'AND'
^, | Bitwise exclusive `OR' and regular `OR'
<=, <, >, >= Comparison operators
<>, ==, != Equality operators
=, %=, /=, //=, -=, +=, *=, **= Assignment operators
is, is not Identity operators
in, not in Membership operators
not or and Logical operators
2/22/2022 64Karpagam Institute of Technology

COMMENTS
•Comment is a piece of program text that the interpreter ignores
but that provides useful documentation to programmers.
•Comments start with the # symbol
Example:
# compute the sum of two numbers
C=A+B
•In this case, the comment appears on a line by itself. We can
also put comments at the end of a line
C=A+B #sum of two numbers
2/22/2022 65Karpagam Institute of Technology

MODULES AND FUNCTIONS
•Module is a file consisting of Python code.
•A module can define functions, classes and variables.
Example:
a="Dora"
def print_func(a):
print ("Hello : ", a)
return
print_func(a)
Output:
Hello : Dora
2/22/2022 66Karpagam Institute of Technology

MODULES AND FUNCTIONS CONTD ..
•The modules can be imported by the following ways:
The import statement
Thefrom...importStatement
The from...import *Statement
2/22/2022 67Karpagam Institute of Technology

MODULES AND FUNCTIONS CONTD ..
The import statement
•WecanuseanyPythonsourcefileasamoduleby
executinganimportstatementinsomeotherPython
sourcefile.
•Theimporthasthefollowingsyntax,
importmodule1,module2,…….moduleN
Example-
importmath
print(math.sqrt(4))
Output
2.0
2/22/2022 68Karpagam Institute of Technology

MODULES AND FUNCTIONS CONTD ..
The from….import statement
•In Python’s from statement, lets us import specific attributes
from a module into the current namespace.
•The from…import statement has the following syntax,
from modnameimport name1, name2,…nameN
Example-
moduleAccess.py
from sample import a,b
print(a.A())
print(b.B())
Output:
Hai
Hello
2/22/2022 69Karpagam Institute of Technology
a.py
def A():
print(“Hai”)
b.py
def B():
print(“Hello”)
sample.py

MODULES AND FUNCTIONS CONTD ..
Thefrom….import*statement
•Itisalsopossibletoimportallnamesfromamodule
intothecurrentnamespacebyusingthefollowing
importstatement,
frommodnameimport*
•Thisprovidesaneasywaytoimportalltheitems
fromamoduleintothecurrentnamespace.
2/22/2022 70Karpagam Institute of Technology

FUNCTION DEFINITION AND USE
FUNCTION
Functionisablockofcode,thatareexecutedwhenitiscalled.
Functionblocksbeginwiththekeyworddeffollowedbythe
functionnameandparentheses().
Anyinputparametersorargumentsshouldbeplacedwithin
theseparentheses.
Thecodeblockwithineveryfunctionstartswithacolon(:)and
isindented.
Thestatementreturn[expression]exitsafunction,optionally
passingbackanexpressiontothecaller.
Areturnstatementwithnoargumentsisthesameasreturn
None.
2/22/2022 71Karpagam Institute of Technology

FUNCTION DEFINITION AND USE CONTD..
Syntax-
def functionname( parameters ):
function_suite
return[expression]
Example-
def printme(str):
print (str)
return
2/22/2022 72Karpagam Institute of Technology

FUNCTION DEFINITION AND USE CONTD..
USES OF FUNCTION-
It makes the program size smaller.
It involves the concept of modularity.
2/22/2022 73Karpagam Institute of Technology

FLOW OF EXECUTION
Theorderinwhichstatementsareexecuted,whichis
calledtheflowofexecution.
Executionalwaysbeginsatthefirststatementofthe
program.
Statementsareexecutedoneatatime,inorderfrom
toptobottom.
Duringfunctioncall,theargumentsintheactual
parametersareassignedtotheformalparameters.
2/22/2022 74Karpagam Institute of Technology

FLOW OF EXECUTION CONTD..
2/22/2022 75Karpagam Institute of Technology

FLOW OF EXECUTION CONTD..
Example-
a=10
b=20
def sum(c,d):
e=c+d
return e
print("Result is :",sum(a,b))
Output:
30
2/22/2022 76Karpagam Institute of Technology

PARAMETERS AND ARGUMENTS
•Parametersprovidethedatacommunicationbetween
callingfunctionandcalledfunction.
Twotypes:
Actualparameter-Thisistheargumentwhichis
usedinfunctioncall.
Formalparameter-Thisistheargumentwhichis
usedinfunctiondefinition.
2/22/2022 77Karpagam Institute of Technology

PARAMETERS AND ARGUMENTS CONTD..
ARGUMENTS -refers to the value.
Types of Arguments
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
2/22/2022 78Karpagam Institute of Technology

PARAMETERS AND ARGUMENTS CONTD..
REQUIREDARGUMENTS
Requiredargumentsaretheargumentspassedtoafunction
incorrectpositionalorder.
Example
defsum(a,b):
c=a+b
returnc
print("Resultis:",sum(10,20))
Output:
30
2/22/2022 79Karpagam Institute of Technology

PARAMETERS AND ARGUMENTS CONTD..
KEYWORD ARGUMENTS
Here,thecalleridentifiestheargumentsbytheparameter
name.
Example
defsum(a,b):
c=a+b
returnc
print("Resultis:",sum(a=10,b=20))
Output:
30
2/22/2022 80Karpagam Institute of Technology

PARAMETERS AND ARGUMENTS CONTD..
DEFAULTARGUMENT:
Defaultargumentisanargumentthatassumesadefault
valueifavalueisnotprovidedinthefunctioncallforthat
argument.
Example
defsum(a=10,b):
c=a+b
returnc
print("Resultis:",sum(20))
Output:
30
2/22/2022 81Karpagam Institute of Technology

PARAMETERS AND ARGUMENTS CONTD..
VARIABLE-LENGTH ARGUMENT
This is used to process a function with more argument.
Syntax for a function with variable length argument,
def functionname([formal_args,]*var_args_tuple):
function_suite
return[expression]
2/22/2022 82Karpagam Institute of Technology

PARAMETERS AND ARGUMENTS CONTD..
Example for Variable-length Argument
def printinfo( arg1,*vartuple):
print ("Output is: ")
print ( arg1)
for varin vartuple:
print (var)
return;
printinfo(10)
printinfo(70,60,50)
Output
10
Output
70
60
50
2/22/2022 83Karpagam Institute of Technology

EXCHANGE THE VALUE OF TWO VARIABLES
With Temporary Variable
x = input("Enter value of x:")
y = input("Enter value of y:")
temp = x
x = y
y = temp
print('The value of x after swapping:',x)
print('The value of y after swapping:',y)
Output
Enter value of x: 67
Enter value of y: 45
The value of x after swapping: 45
The value of y after swapping: 67
2/22/2022 84Karpagam Institute of Technology

EXCHANGE THE VALUE OF TWO VARIABLES CONTD..
Without Temporary Variable
x = input("Enter value of x:")
y = input("Enter value of y:")
x= x + y
y = x -y
x = x -y
print('The value of x after swapping:',x)
print('The value of y after swapping:',y)
Output
Enter value of x: 67
Enter value of y: 45
The value of x after swapping: 45
The value of y after swapping: 67
2/22/2022 85Karpagam Institute of Technology

CIRCULATE THE VALUES OF N NUMBERS
def circulate(A,N):
for i in range of(0,N):
j=len(A)-1
while j>0:
temp=A[j]
A[j]=A[j-1]
A[j-1]=temp
j=j-1
print(‘Circulation\t’,A)
return
A=[91,92,93,94,95]
n=int(input(“Enter n:”))
circulate(A,n)
Output
n=2
Circulation 95,91,92,93,94
Circulation 94,95,91,92,93
2/22/2022 86Karpagam Institute of Technology

DISTANCE BETWEEN TWO POINTS
import math
x1=int(input("Enter the X-Coordinate of first point"))
y1=int(input("Enter the Y-Coordinate of first point"))
x2=int(input("Enter the X-Coordinate of Second point"))
y2=int(input("Enter the Y-Coordinate of Second point"))
distance = math.sqrt( ((x1-x2)**2)+((y1-y2)**2) )
print(distance)
Output
Enter the X-Coordinate of first point 4
Enter the Y-Coordinate of first point 0
Enter the X-Coordinate of Second point 6
Enter the Y-Coordinate of Second point 6
6.324555320336759
2/22/2022 87Karpagam Institute of Technology

VIDEO TUTORIAL
S.No Topic Link
1Interpreter and Interactive modehttps://youtu.be/3lvgY5V8494
2Operator and it's types with their
Precedence
https://youtu.be/ljaw6cUobtU
3Circulate the value of n numbers
using slicing operator
https://youtu.be/1Y46EaJAQ4c
4Distance between two pointshttps://youtu.be/qeZ5kiKJe7c
2/22/2022 88Karpagam Institute of Technology

SUMMARY
Python Interpreter and Interactive mode
Values and Data types
Operators and its Precedence
Modules and Functions
Function Parameters and Arguments
Illustrative Problems
2/22/2022 89Karpagam Institute of Technology

ASSIGNMENT QUESTIONS
S.No Questions Blooms Level
1Write a Python programs to check
whether the given number is palindrome
or not
K3
2Apply the concept of Modules for airlines
system
K3
3Distinguish between Interpretermode and
Interactive mode
K4
4Develop a Python program for finding
Fibonacci sequence of n numbers using
function with recursion
K5
2/22/2022 90Karpagam Institute of Technology

QUIZ -TEST YOUR KNOWLEDGE
•https://forms.gle/uP745eEsYzko6Y2U9
2/22/2022 91Karpagam Institute of Technology

UNIT III CONTROL FLOW, FUNCTIONS
SYLLABUS
Conditionals: Boolean values and operators, conditional (if),
alternative (if-else), chainedconditional(if-elif-else);
Iteration: state, while, for, break, continue, pass; Fruitful
functions: returnvalues, parameters, local and global scope,
function composition, recursion; Strings: string slices,
immutability, string functions and methods, string module;
Lists as arrays.
Illustrativeprograms: square root, gcd, exponentiation, sum
an array of numbers, linear search, binary search.
2/22/2022 92Karpagam Insitute of Technology2/22/2022 92

BOOLEAN EXPRESSION
ABooleanexpressionisaexpressionthatresultsineithertrue
orfalse.
Itusesthe==operatorwhichcomparestwooperandsand
procedurestrueifbothareequalotherwisefalse.
93
KarpagamInstitute of Technology
2/22/2022

CONTROL FLOW
•Itisastatementthatdeterminesthecontrolflowofasetof
instructions.,(ie)itdecidesthesequenceinwhichthe
instructionsinaprogramaretobeexecuted.
•Itcaneithercompriseofoneormoreinstructions.Three
fundamentalcontrolstatementsare
Sequential
Selection
Iterativecontrol
94KarpagamInstitute of Technology2/22/2022

TYPES OF DECISION CONTROL STATEMENTS
95
KarpagamInstitute of Technology
2/22/2022

SELECTION OR CONDITIONAL BRANCHING
STATEMENT
•Thedecisioncontrolstatementsusuallyjumpsfromonepartof
thecodetoanotherdependingonwhetheraparticular
conditionissatisfiedornot.
•Pythonselectionstatementsare:
Ifstatement
If-elsestatement
If-elif-elsestatement
Nested-ifstatement
96KarpagamInstitute of Technology
2/22/2022

ITERATIVE STATEMENTS
•Iterativestatementsaredecisioncontrolstatementsthatare
usedtorepeattheexecutionofalistofstatements.The
followingarethetypesofiterativestatements.
whileloop
forloop
97
KarpagamInstitute of Technology
2/22/2022

WHILE LOOP
•Thewhileloopprovidesamechanismtorepeatoneormore
statementswhileaparticularconditionistrue.
•Syntax:
Statement X
while (condition):
Statements block
98KarpagamInstitute of Technology
2/22/2022

FLOWCHART FOR WHILE LOOP
99
KarpagamInstitute of Technology
2/22/2022

EXAMPLE FOR WHILE LOOP
num= 1
while num < 10:
print(num)
num = num + 3
Ouput:
1
4
7
100KarpagamInstitute of Technology
2/22/2022

EXAMPLE FOR WHILE LOOP WITH ELSE STATEMENT
num = 10
while num > 6:
print(num)
num = num-1
else:
print("loop is finished")
Output:
10
9
8
7
loop is finished
101KarpagamInstitute of Technology
2/22/2022

FOR LOOP
•Itprovidesamechanismtorepeatataskuntilaparticular
conditionistrue.
•Itisknownasdeterminateordefiniteloopbecausethe
programmerknowsexactlyhowmanytimestheloopwill
repeat.
Syntax1:
forloop_control_varinsequence:
Statementblock
102
KarpagamInstitute of Technology
2/22/2022

FOR LOOP CONTD..
Syntax 2:
for variable in range(beg,end,[step]):
Statements
103KarpagamInstitute of Technology
2/22/2022

FLOWCHART OF FOR LOOP
104
KarpagamInstitute of Technology2/22/2022

EXAMPLE OF FOR LOOP
numbers = [1, 2, 4, 6, 11, 20]
sq = 0
for valin numbers:
sq = val* val
print(sq)
105KarpagamInstitute of Technology2/22/2022
Output:
1
4
16
36
121
400

RANGE( ) IN FOR LOOP
•range(n): generates a set of whole numbers starting
from 0 to (n-1).
For example:
range(8) is equivalent to [0, 1, 2, 3, 4, 5, 6, 7]
•range(start, stop): generates a set of whole numbers
starting from start to stop-1.
For example:
range(5, 9) is equivalent to [5, 6, 7, 8]
106
KarpagamInstitute of Technology
2/22/2022

RANGE( ) IN FOR LOOP CONTD..
•range(start,stop,step_size):Thedefaultstep_sizeis1
whichiswhywhenwedidn’tspecifythestep_size,the
numbersgeneratedarehavingdifferenceof1.However
byspecifyingstep_sizewecangeneratenumbershaving
thedifferenceofstep_size.
Forexample:
range(1,10,2)isequivalentto[1,3,5,7,9]
107KarpagamInstitute of Technology
2/22/2022

EXAMPLE OF FOR LOOP WITH RANGE( )
sum = 0
for valin range(1, 6):
sum = sum + val
print(sum)
Output:
15
108
KarpagamInstitute of Technology2/22/2022

EXAMPLE OF FOR LOOP WITH ELSE BLOCK
for valin range(5):
print(val)
else:
print("The loop has completed execution")
Output:
0
1
2
3
4
The loop has completed execution
109
KarpagamInstitute of Technology2/22/2022

BREAK STATEMENT
•Thebreakstatementisusedtoterminatethe
executionoftheloop.
•Whenacompilerencountersabreakstatement,the
controlpassestothestatementthatfollowstheloop
inwhichthebreakstatementappears.
•Syntax:-break
110KarpagamInstitute of Technology2/22/2022

FLOWCHART FOR BREAK STATEMENT
111KarpagamInstitute of Technology2/22/2022

EXAMPLE FOR BREAK STATEMENT
# program to display all the elements before number 88
for numin [11, 9, 88, 10, 90, 3, 19]:
print(num)
if(num==88):
print("The number 88 is found")
print("Terminating the loop")
break
112KarpagamInstitute of Technology
2/22/2022
Output:-
11
9
88
The number 88 is found
Terminating the loop

CONTINUE STATEMENT
•Thecontinuestatementcanonlyappearinthebody
ofaloop.
•Whenacompilerencountersacontinuestatement,
thentherestofthestatementsintheloopareskipped
andthecontrolisunconditionallytransferredtothe
loop-continuationportionofthenearestloop.
•Syntax:continue
113KarpagamInstitute of Technology2/22/2022

FLOWCHART FOR CONTINUE STATEMENT
114KarpagamInstitute of Technology2/22/2022

EXAMPLE FOR CONTINUE STATEMENT
# program to display only odd numbers
for numin [20, 11, 9, 66, 4, 89, 44]:
if (num%2 == 0):
continue
print(num)
115
KarpagamInstitute of Technology2/22/2022
Output
11
9
89

PASS STATEMENT
•Thepassstatementactsasaplaceholderandusuallyused
whenthereisnoneedofcodebutastatementisstillrequiredto
makeacodesyntacticallycorrect.
•Example:-
fornumin[20,11,9,66,4,89,44]:
ifnum%2==0:
pass
else:
print(num)
Output:
11
9
89
116KarpagamInstitute of Technology2/22/2022

STRINGS
•Stringisasequenceofcharacters.
•Stringmaycontainalphabets,numbersandspecial
characters.
•Stringvaluemustbeenclosedwithineithersingle
quotesorwithindoublequotes.
•Stringisimmutableinnature.(i.e).,oncecreated
cannotbeabletoeditwhenitisstoredinavariable.
Example:
Letter = “A”
Name = ‘python’
117
KarpagamInstitute of Technology
2/22/2022

READING STRING VALUE FROM THE USER:
•Usinginput()functionwecanreadstringvaluefrom
theuser.
Syntax:
Variable_name=input(“Enterthevalues”)
Example:
Name=input(“Enterthename”)
print(“Welcome”,name)
Output:
Enterthename:python
Welcomepython
118KarpagamInstitute of Technology2/22/2022

INDEX OPERATION:
•Eachcharactercanbeaccessedthroughindexoperator.
Syntax:
String_variable_name[index]
•Indexvaluestartsatzeroandlastindexvalueis(lengthof
thestring-1)
Example:
119KarpagamInstitute of Technology2/22/2022

STRING OPERATIONS
120KarpagamInstitute of Technology2/22/2022

CONCATENATION OF TWO OR MORE STRINGS
•Joiningoftwoormorestringsintoasingleoneis
calledconcatenation.
Syntax:String2=string1+string2
Example:
str1 = 'Hello'
str2 ='World!'
print('str1+str2=',str1+str2)
Output:
HelloWorld!
121KarpagamInstitute of Technology2/22/2022

REPETITION OPERATOR(*):
•Itisusedtoconcatenatethesamestringmultiple
times.
Syntax:
String2=String1*integervalue
Example:
str1='Hello'
print('str1*3=',str1*3)
Output:
HelloHelloHello
122KarpagamInstitute of Technology2/22/2022

STRING SLICING
•Slicingoperationsisusedtoselect/return/slice
theparticularsubstringbasedonuser
requirements.
•Asegmentofthestringiscalledslice.
Syntax:
String_variable_name[start:end:stepvalue]
•Herealltheparameters/variablesareoptional
•Thedefaultvalueforstartiszeroandendisend-1
•Thedefaultvalueforstepis1.
123KarpagamInstitute of Technology2/22/2022

EXAMPLE FOR STRING SLICING
var1 = 'Hello World!’
var2 = "Python Programming"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]
Output:
H
ytho
124KarpagamInstitute of Technology2/22/2022

STRING COMPARISON:
•We can compare two strings by using comparison
operators such as ==,!=,<,<=,>,>=.
•Python compares strings based on their corresponding
ASCII values.
•For ‘a’ ASCII value is 97 and ‘A’ ASCII value is 65.
125KarpagamInstitute of Technology2/22/2022

EXAMPLE FOR STRING COMPARISON
str1=”green”
str2=”glow”
print(“is both string are equal:”, str1==str2)
print(“is both string are not equal:”, str1!=str2)
print(“is str1>str2:”,str1>str2)
print(“is str1>str2:”,str1<str2)
126
KarpagamInstitute of Technology2/22/2022
Output:-
is both string are equal:False
is both string are not equal:True
is str1>str2:True
is str1>str2:False

STRING ITERATION:
•Wecanusforlooptotraverseallthecharactersinthe
stringsequentially.
•Syntax1:
forvar_nameinstring_varaible_name:
statements
•Syntax2:
forvar_nameinrange(initial,final,stepvalue):
statements
127KarpagamInstitute of Technology2/22/2022

PROGRAM TO COUNT THE NUMBER OF
CHARACTERS IN A STRING
str=input(“enter any string:”)
count=0
for letter in str:
if(letter):
count=count+1
print(“total number of characters in string is:”, count)
Output:
Enter any string:python
Total number of characters in string is:6
128KarpagamInstitute of Technology2/22/2022

COUNT THE NUMBER OF CHARACTERS IN A STRING
USING RANGE FUNCTION
str=input(“enter any string:”)
count=0
for letter in range(0,len(str)+1,1):
if(letter):
count=count+1
print(“total number of characters in string is:”, count)
Output:
Enter any string: python
Total number of characters in string is:6
129KarpagamInstitute of Technology2/22/2022

STRING IMMUTABILITY
•Stringsareimmutableinnature.
•Wecannoteditthestringvalueonceitisassignedtovariable.
•Ifwetrytoassignorreplaceavalueinthestring,itdisplays
anerrormessagethatstrisnotamutableobject.
Program:
str=“welcome”
print(str[3])
str[3]=“c”#assigningvaluectoindex3place
print(str)
Output:
c
Traceback(mostrecentcalllast):
str[3]=”c’#assigningvaluectoindex3place
TypeError:’str’objectdoesnotsupportitemassignment
130KarpagamInstitute of Technology2/22/2022

STRING MODULES
•Stringmodulescontainanumberoffunctionsto
processstandardpythonstring.
•Thiscanbedonebyimportingstringfunction.
Syntax:
import string
131KarpagamInstitute of Technology2/22/2022

LIST AS ARRAY:
•Arrayisacollectionofsimilardataitemsthatare
storedunderacommonname.
•Pythonisnotprovidingarraydatatyperatherthanit
providesaLIST.
Implementingarrayinpythonone-dimensionallist:
•Arrayscanbeimplementedasonedimensionallist.
•Ex:Price_list=[70,80,90,93.5,30.456]
132KarpagamInstitute of Technology2/22/2022

MINIMUM VALUE IN THE LIST WITHOUT USING
INBUILT FUNCTION:
price_list=[70,80,90,93.5,30.456]
min=price_list[0]
for min_valuein price_list:
if min>min_value:
min=min_value
print(“minimum value in the list is:”,min)
OUTPUT:
minimum value in the list is:34.56
133KarpagamInstitute of Technology2/22/2022

IMPLEMENTING ARRAY IN PYTHON AS TWO -
DIMENSIONAL LIST:
Example:
Two_dim_array_list=[[1,2],[3,4]]
Program:
two_dim=[[1,2],[3,4]]
print(“original 2 dimensional list:”)
for iin range(len(two_dim)):
for j in range(len(two_dim[i])):
print(two_dim[i][j],end=“”)
print(“\n”)
134KarpagamInstitute of Technology2/22/2022

SQUARE ROOT OF A GIVEN NUMBER:
num=float(input("Enter a Number"))
num_sqrt=num**0.5
print("The square root of %0.3f is %0.3f"%(num,num_sqrt))
Output--
135Karpagam Institute of Technology2/22/2022

GCD OF TWO NUMBERS
def gcd(a, b):
if(b==0):
return a
else:
return gcd(b, a%b)
a=int(input("Enter First number"))
b=int(input("Enter Second number"))
GCD=gcd(a, b)
print("GCD is:")
print(GCD)
2/22/2022 136KarpagamInstitute of Technology

EXPONENTIATION
import math # This will import math module
print ("math.pow(100,2): ", math.pow(100,2))
print ("math.pow(100,-2): ",math.pow(100,-2))
print ("math,pow(2,4): ",math.pow(2,4))
print ("math.pow(3,0): ",math.pow(3,0))
137KarpagamInstitute of Technology2/22/2022

SUM AN ARRAY NUMBERS
def listsum(numlist):
sum=0
for i in numberlist:
sum=sum+i
return sum
print(listsum([1,3,5,9]))
Output:
18
138KarpagamInstitute of Technology2/22/2022

LINEAR SEARCH
my_data=[89,45,9,21,34]
num=int(input(“Enter search num:”))
for i in range (0, len(my_data)):
if num==my_data[i]:
print(“Item is located at position=,”i)
else:
print(“Item not found”)
139KarpagamInstitute of Technology2/22/2022

BINARY SEARCH
list=[10,20,30,40]
x=int(input(“Enter the element to search:”)
first=0
last=len(list-1)
while(first<=last):
mid=(first+last)//2
if(x==list[mid]):
print(“The element is found at the index:”,mid)
break
elif(x<list[mid]):
last=mid-1
else:
first=mid+1
else:
print(“The element is not found in the list”)
140KarpagamInstitute of Technology2/22/2022

VIDEO TUTORIAL
S.NO TOPIC LINK
1Boolean Values and
Operators
https://youtu.be/7vy_GffZZTg
2Loops in Python https://www.youtube.com/watch?v=
zFvoXxeoosI
3Fruitful Functions https://youtu.be/hMGc19ZYzDM
4Stringsin Python https://www.youtube.com/watch?v=
QGLNQwfTO2w
5Linear Search https://youtu.be/fHMXsGkN5cg
2/22/2022 141Karpagam Institute of Technology

SUMMARY
•Pythonbranchingstatements
•Pythonloopingstatements
•Stringsanditsmethods.
•IllustrativePrograms
2/22/2022
KarpagamInstitute of Technology
142

ASSIGNMENT QUESTIONS
S.NO QUESTIONS BLOOMS LEVEL
1 WriteaPythonprogramtocheckwhethera
givennumberisaperfectnumber
K3
2 WriteaPythonprogramtocalculatethenumber
ofwordsandnumberofcharacterspresentina
string
K3
3 WriteaPythoncodetocounttheoccurrencesof
eachwordinagivenstringsequence
K3
4 DevelopaPythoncodetocheckwhetherastring
ispalindromeornot
K5
5 DevelopaPythonprogramtodetectwhether
twostringsareanagrams
K5
2/22/2022 143KarpagamInstitute of Technology

QUIZ-TEST YOUR KNOWLEDGE
•https://docs.google.com/forms/d/e/1FAIpQLSc
Yn1TS4wfhudU0CgVwuCGlEZPQmchmz1_l
av0Q2oiONI8Gbw/viewform
2/22/2022 KarpagamInstitute of Technology 144

THANK YOU
2/22/2022 Karpagam Insitute of Technology 1452/22/2022 145
Tags