1. 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
2. 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 strategies for developing algorithms (iteration,
recursion).
Illustrative problems: find minimum in a list, insert a card in
a list of sorted cards, guess an integer number in a range,
Towers of Hanoi.
2/22/2022 Karpagam Insitute of Technology 2
2/22/2022 2
4. 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 4
Karpagam Institute of Technology
5. ADVANTAGES OF ALGORITHM
Easy to understand.
Programs can be easily developed.
2/22/2022 5
Karpagam Institute of Technology
6. 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 6
Karpagam Institute of Technology
7. BUILDING BLOCKS OF ALGORITHMS
Statement
State
Control Flow
Functions
2/22/2022 7
Karpagam Institute of Technology
8. 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 8
Karpagam Institute of Technology
9. STATE
• Transition from one process to another process
under specified condition within a time is
called state.
2/22/2022 9
Karpagam Institute of Technology
10. CONTROL FLOW
• The process of executing the individual
statements in a given order is called control
flow.
• The control can be executed in three ways
Sequence
Selection
Iteration
2/22/2022 10
Karpagam Institute of Technology
11. SEQUENCE
• All the instructions are executed one after another
is called sequence execution.
• Example: Sum of two numbers:
Step 1: Start
Step 2: Read the values of a and b
Step 3: calculate c=a+b
Step 4: Display c
Step 5: Stop
2/22/2022 11
Karpagam Institute of Technology
12. SELECTION
• Selection execution is based upon the condition.
• If the conditional test is true, one part of the
program will be executed.
• Otherwise, it will execute the other part of the
program.
2/22/2022 12
Karpagam Institute of Technology
13. 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 13
Karpagam Institute of Technology
14. ITERATION
• Set of statements are executed again and again based upon
conditional test.
• Write an algorithm to print all ‘n’ natural numbers
Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 7
Step 5: Print i value and increment i value by 1
Step 6: go to step 4
Step 7: Stop
2/22/2022 14
Karpagam Institute of Technology
15. FUNCTIONS
• Function is a sub program which consists of block of code(set of
instructions) that performs a particular task.
• Algorithm for addition of two numbers using function
Main function
Step 1: Start
Step 2: Call the function add( )
Step 3: Stop
Sub function
Step 1: Function start
Step 2: Get a, b Values
Step 3: add c=a+b
Step 4: Print c
Step 5: Return
2/22/2022 15
Karpagam Institute of Technology
16. FLOW CHART
• Pictorial representation of an algorithm.
• Since it is a visual representation, it helps to understand the logic of
the program.
2/22/2022 16
Karpagam Institute of Technology
17. Draw a flowchart to find the sum and average
of given two numbers.
2/22/2022 17
Karpagam Institute of Technology
18. Draw a flowchart to find the smallest of given
two numbers.
2/22/2022 18
Karpagam Institute of Technology
19. PSEUDOCODE
• Pseudo code only describes the logic to develop a program
and it can be translated to any computer language code.
• Keywords should be highlighted by capitalizing them.
• Using Keywords:
Input : READ, OBTAIN, GET
Output : PRINT, DISPLAY, SHOW
Compute : COMPUTE, CALCULATE, DETERMINE
Initialize : SET, INITIALIZE
Add one : INCREMENT, BUMP
2/22/2022 19
Karpagam Institute of Technology
20. 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 20
Karpagam Institute of Technology
21. PROGRAMMING LANGUAGE
• Computer programming languages are used to communicate
instructions to a computer.
Interpreted Programming Languages
Functional Programming Languages
Compiled Programming Languages
Procedural Programming Languages
Scripting Programming Languages
Markup Programming Languages
Logic-Based Programming Languages
Concurrent Programming Languages
Object-Oriented Programming Languages
2/22/2022 21
Karpagam Institute of Technology
22. PROGRAMMING LANGUAGE CONTD..
Interpreted Programming Languages
• An interpreted language execute instructions
directly, without previously compiling a
program into machine-language instructions.
• Examples: APL, BASIC, ICI, J, Lisp, Lua, M,
Pascal, Perl, Python, Ruby, S-Lang, spin
2/22/2022 22
Karpagam Institute of Technology
23. PROGRAMMING LANGUAGE CONTD..
Functional Programming Language:
• They focus on the application of functions.
• Many functional programming languages are bound
to mathematical calculations.
Examples:-
• ML, Joy, Kite, Clean, OPAL, Q
2/22/2022 23
Karpagam Institute of Technology
24. PROGRAMMING LANGUAGE CONTD..
Compiled Programming Languages
• A compiled language is a programming
language whose implementations are typically
compilers.
• Examples: Ada, ALGOL, C, C++, C#,
COBOL, etc.
2/22/2022 24
Karpagam Institute of Technology
25. PROGRAMMING LANGUAGE CONTD..
Procedural Programming Languages
• Procedural (imperative) programming implies
specifying the steps that the programs should
take to reach to an intended state.
• Examples: Bliss, ChucK, CLIST, HyperTalk,
Modula-2, Oberon, Component, Pascal,
MATLAB, PL/C, PL/I, Rapira, RPG
2/22/2022 25
Karpagam Institute of Technology
26. PROGRAMMING LANGUAGE CONTD..
Scripting Languages
• Scripting languages are programming
languages that control an application.
• Examples: AppleScript, BeanShell,
ColdFusion, F-Script, JASS, PHP, VBScript,
Windows PowerShell
2/22/2022 26
Karpagam Institute of Technology
27. PROGRAMMING LANGUAGE CONTD..
Markup Languages
• A markup language is an artificial language
that uses annotations to text that define how
the text is to be displayed.
• Examples: Curl, SGML, HTML, XML,
XHTML
2/22/2022 27
Karpagam Institute of Technology
28. PROGRAMMING LANGUAGE CONTD..
Logic-based Programming Languages
• Logic programming is a type of programming
paradigm which is largely based on formal
logic.
• Examples: ALF, Fril, Janus, Oz, Poplog,
Prolog, ROOP
2/22/2022 28
Karpagam Institute of Technology
29. PROGRAMMING LANGUAGE CONTD..
Concurrent Programming Languages:
• It is a computer programming technique, which
executes the operation concurrently – either within
single computer or across number of systems.
Examples:
• ABCL, Concurrent Pascal, E, Joule, SALSA, Pict,
SR, etc.
2/22/2022 29
Karpagam Institute of Technology
30. PROGRAMMING LANGUAGE CONTD..
Object-Oriented Programming Languages
• Object-oriented programming (OOP) is a
programming paradigm based on the concept of
“objects”, which may contain data, in the form of
fields, often known as attributes; and code, in the
form of procedures, often known as methods.
• Examples: IO, Slate, Self, Scala, Prograph,
Oxygene, Moto, MOO, Lava, BETA, Agora
2/22/2022 30
Karpagam Institute of Technology
31. ALGORITHMIC PROBLEM SOLVING
➢Understanding the problem
➢Ascertain the capabilities of the computational
device
➢Exact /approximate solution
➢Decide on the appropriate data structure
➢Algorithm design techniques
➢Methods of specifying an algorithm
➢Proving an algorithms correctness
➢Analyzing an algorithm
2/22/2022 31
Karpagam Institute of Technology
32. UNDERSTANDING THE PROBLEM
• The problem given should be clearly and
completely understood.
2/22/2022 32
Karpagam Institute of Technology
33. 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 33
Karpagam Institute of Technology
34. EXACT /APPROXIMATE SOLUTION
• Once algorithm is devised, it is necessary to show that
how it computes answer for all the possible legal
inputs.
• Examples of Exact solution problems are
i) Computing addition of 2 numbers.
ii) Find the given number is prime or not.
Examples of Approximate solution problems where an
exact solution cannot be obtained are
i) Finding a square root of number.
ii) Solutions of non linear equations.
2/22/2022 34
Karpagam Institute of Technology
35. DECIDE ON THE APPROPRIATE DATA
STRUCTURE
• Data type is a well defined collection of data with the well
defined set of operations on it.
• A data structure is basically a group of data elements.
• The Elementary data structures are as follows,
List: Allows fast access of data
Sets: Treat data as element of a set. Allows application of
operations such as intersection, Union and equivalence.
Dictionaries: Allows data to be stored as a key value pair.
2/22/2022 35
Karpagam Institute of Technology
36. ALGORITHM DESIGN TECHNIQUES
• Creating an algorithm is an art.
• By mastering these design strategies, it will
become easier to devise new and useful
algorithms.
2/22/2022 36
Karpagam Institute of Technology
37. METHODS OF SPECIFYING AN
ALGORITHM
• Use of natural language or pseudocode.
• Flow Chart
2/22/2022 37
Karpagam Institute of Technology
38. PROVING AN ALGORITHMS
CORRECTNESS
• It is necessary to prove that algorithm
computes solutions for all the possible valid
input.
2/22/2022 38
Karpagam Institute of Technology
39. ANALYZING THE PERFORMANCE OF
ALGORITHMS
• An algorithm is analyzed to measure its
performance in terms of CPU time and memory
space required to execute that algorithm.
2/22/2022 39
Karpagam Institute of Technology
40. SIMPLE STRATEGIES FOR DEVELOPING
ALGORITHMS (ITERATION,
RECURSION)
ITERATION
• A Loop is one or more instructions that the computer
performs repeatedly.
• Algorithm: Write the algorithm to print “1 to 5”
Step1 : Start
Step2 : Initialize the value of i as 1
Step3 : Print i and increment the value of i
Step 4: Repeat the Step 3 until the value of i <=5.
Step 5 : Stop
2/22/2022 40
Karpagam Institute of Technology
41. RECURSION
• A function that calls itself is known as recursive function and the
phenomenon is called as recursion.
• Algorithm: Write an algorithm to find the factorial of a given
number
Main Program:
Step 1: Start
Step 2: Read n
Step 3: Call the sub program as f=fact(n)
Step 4 : print f value
Step 5: Stop
Sub Program:
Step 1: If n==0 or n==1 return 1 to the main program otherwise go to
step 2
Step 2: return n*fact(n-1) to main program
2/22/2022 41
Karpagam Institute of Technology
42. FINDING MINIMUM IN A LIST
Step 1:Start
Step 2: Read the list of numbers as L
Step 3: Set Min to list[0]
Step 4: For each number x in the list L, compare it
to min
Step 4a: If x is smaller, then assign min to x
Step 5: Print min
Step 6: Stop
2/22/2022 42
Karpagam Institute of Technology
43. GUESS AN INTEGER NUMBER IN A
RANGE
Step 1: Start
Step 2: Generate a random number in between 1 and 100
Step 3: Get the guessed number from the user
Step 4:If the random number is equal to the guessed number
print guessing is correct.
Step 5: Otherwise If the random number is greater than the
guessed number print guessing is too high and go to
step 7
Step 6: Otherwise print guessing is too high and go to step 7.
Step 7: Stop
2/22/2022 43
Karpagam Institute of Technology
44. INSERT A CARD IN A LIST OF SORTED
CARDS
Step 1 - Start
Step 2 - Read the list of sorted cards.
Step 3 - If it is the first card, it is already sorted. return 1;
Step 4 - Pick next card
Step 5 - Compare with all cards in the sorted sub-list
Step 6- Shift all the cards in the sorted sub-list that is
greater than the value of the card to be inserted.
Step 5 - Insert the card
Step 6 - Repeat until list is sorted.
Step 7 - Stop
2/22/2022 44
Karpagam Institute of Technology
45. TOWERS OF HANOI
• Problem:
• Tower of Hanoi is a mathematical puzzle with
three rods and ‘n’ number of disks.
• These disks are in different sizes and stacked
upon in an ascending order, i.e the smaller one
sits over the larger one.
• The objective is to move all the disks to some
another tower without violating the sequence
of arrangement.
2/22/2022 45
Karpagam Institute of Technology
46. 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 46
Karpagam Institute of Technology
48. VIDEO TUTORIAL
S.NO TOPIC LINK
1 Minimum in a list https://youtu.be/5Y1rxCMY_jU
2 Insert a Card in a list of
Sorted Cards
https://youtu.be/Mow8rdOKrbY
3 Guess an integer number
in a range
https://youtu.be/pmDKRJdqT1E
4 Tower of Hanoni https://youtu.be/hKUwLe7bpwo
2/22/2022 48
Karpagam Institute of Technology
49. 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 49
2/22/2022 49
50. ASSIGNMENT QUESTIONS
S.NO QUESTIONS BLOOMS LEVEL
1 Apply the rules of an algorithm and
pseudocode to find whether the given
number is positive, negative and zero.
K3
2 Apply the rules of an algorithm and
pseudocode to find the factorial of a given
number using recursion.
K3
3 Write a pseudo code for converting celsius
of a given value into fahrenheit.
K3
4 Develop a flow chart for performing
Towers of Hanoi operation.
K5
5 Design a flow chart for calculating simple
interest
K5
2/22/2022 50
Karpagam Institute of Technology
51. 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 51
2/22/2022 51
52. UNIT II DATA, EXPRESSIONS, STATEMENTS
SYLLABUS:
Python interpreter and interactive mode; values and types: int,
float, boolean, string, and list; variables, expressions, statements,
Tuple assignment, precedence of operators, comments; modules
and functions, function definition and use, flow of execution,
parameters and arguments;
Illustrative programs: exchange the values of two variables,
circulate the values of n variables, distance between two points.
2/22/2022 52
2/22/2022 52
Karpagam Institute of Technology
53. PYTHON INTERPRETER AND INTERACTIVE MODE
INTERACTIVE MODE PROGRAMMING:
• Interactive mode is a command line shell which gives
immediate feedback for each statement.
• In this mode, the prompts for the next command usually have
three greater-than signs (>>>).
• Example- A sample interactive session:
>>> 5
5
>>> print(5*7)
35
>>> "hello" * 4
'hellohellohellohello'
2/22/2022 53
Karpagam Institute of Technology
54. 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 54
Karpagam Institute of Technology
55. 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 55
Karpagam 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”}
56. 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 56
Karpagam Institute of Technology
57. 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 – Collection of elements in curly braces { } with key:value
pair
>>>a={1: “hai”, 2: “welcome”}
>>>type(a)
<type ‘dict’>
2/22/2022 57
Karpagam Institute of Technology
58. 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 58
Karpagam Institute of Technology
59. EXPRESSIONS
• An expression is a combination of values, variables,
and operators.
• Examples:
–17
–x
–x + 17
2/22/2022 59
Karpagam Institute of Technology
60. STATEMENTS
• Each and every instruction or line in the program is
called as statements.
• Example:
A=10 #assignment statement
B=20 #assignment statement
C=A+B #assignment statement
print(C) #print statement
Output :
30 #output statement
2/22/2022 60
Karpagam Institute of Technology
61. TUPLE ASSIGNMENT
• Python has a very powerful tuple assignment feature 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 swap a and b:
a=10
b=20
temp = a
a = b
b = temp
• Tuple assignment solves this problem neatly:
(a,b) = (b,a)
2/22/2022 61
Karpagam Institute of Technology
62. 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 62
Karpagam Institute of Technology
63. 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 and the result is multiplied by pi.
2/22/2022 63
Karpagam Institute of Technology
64. PRECEDENCE OF OPERATORS CONTD..
Operator Description
** Exponentiation raise 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 64
Karpagam Institute of Technology
65. 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 65
Karpagam Institute of Technology
66. 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 66
Karpagam Institute of Technology
67. MODULES AND FUNCTIONS CONTD..
• The modules can be imported by the following ways:
The import statement
The from...import Statement
The from...import * Statement
2/22/2022 67
Karpagam Institute of Technology
68. MODULES AND FUNCTIONS CONTD..
The import statement
• We can use any Python source file as a module by
executing an import statement in some other Python
source file.
• The import has the following syntax,
import module1, module2, …….moduleN
Example-
import math
print(math.sqrt(4))
Output
2.0
2/22/2022 68
Karpagam Institute of Technology
69. 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 modname import name1, name2,…nameN
Example-
moduleAccess.py
from sample import a,b
print(a.A())
print(b.B())
Output:
Hai
Hello
2/22/2022 69
Karpagam Institute of Technology
a.py
def A():
print(“Hai”)
b.py
def B():
print(“Hello”)
sample.py
70. MODULES AND FUNCTIONS CONTD..
The from….import* statement
• It is also possible to import all names from a module
into the current namespace by using the following
import statement,
from modname import*
• This provides an easy way to import all the items
from a module into the current namespace.
2/22/2022 70
Karpagam Institute of Technology
71. FUNCTION DEFINITION AND USE
FUNCTION
Function is a block of code, that are executed when it is called.
Function blocks begin with the keyword def followed by the
function name and parentheses ( ).
Any input parameters or arguments should be placed within
these parentheses.
The code block within every function starts with a colon (:) and
is indented.
The statement return [expression] exits a function, optionally
passing back an expression to the caller.
A return statement with no arguments is the same as return
None.
2/22/2022 71
Karpagam Institute of Technology
72. FUNCTION DEFINITION AND USE CONTD..
Syntax-
def functionname( parameters ):
function_suite
return[expression]
Example-
def printme(str):
print (str)
return
2/22/2022 72
Karpagam Institute of Technology
73. FUNCTION DEFINITION AND USE CONTD..
USES OF FUNCTION-
It makes the program size smaller.
It involves the concept of modularity.
2/22/2022 73
Karpagam Institute of Technology
74. FLOW OF EXECUTION
The order in which statements are executed, which is
called the flow of execution.
Execution always begins at the first statement of the
program.
Statements are executed one at a time, in order from
top to bottom.
During function call, the arguments in the actual
parameters are assigned to the formal parameters.
2/22/2022 74
Karpagam Institute of Technology
75. FLOW OF EXECUTION CONTD..
2/22/2022 75
Karpagam Institute of Technology
76. 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 76
Karpagam Institute of Technology
77. PARAMETERS AND ARGUMENTS
• Parameters provide the data communication between
calling function and called function.
Two types:
Actual parameter -This is the argument which is
used in function call.
Formal parameter - This is the argument which is
used in function definition.
2/22/2022 77
Karpagam Institute of Technology
78. PARAMETERS AND ARGUMENTS CONTD..
ARGUMENTS - refers to the value.
Types of Arguments
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
2/22/2022 78
Karpagam Institute of Technology
79. PARAMETERS AND ARGUMENTS CONTD..
REQUIRED ARGUMENTS
Required arguments are the arguments passed to a function
in correct positional order.
Example
def sum(a,b):
c=a+b
return c
print("Result is:", sum(10,20))
Output:
30
2/22/2022 79
Karpagam Institute of Technology
80. PARAMETERS AND ARGUMENTS CONTD..
KEYWORD ARGUMENTS
Here, the caller identifies the arguments by the parameter
name.
Example
def sum(a,b):
c=a+b
return c
print("Result is:", sum(a=10,b=20))
Output:
30
2/22/2022 80
Karpagam Institute of Technology
81. PARAMETERS AND ARGUMENTS CONTD..
DEFAULT ARGUMENT:
Default argument is an argument that assumes a default
value if a value is not provided in the function call for that
argument.
Example
def sum(a=10,b):
c=a+b
return c
print("Result is:", sum(20))
Output:
30
2/22/2022 81
Karpagam Institute of Technology
82. 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 82
Karpagam Institute of Technology
83. PARAMETERS AND ARGUMENTS CONTD..
Example for Variable-length Argument
def printinfo( arg1,*vartuple):
print ("Output is: ")
print ( arg1)
for var in vartuple:
print (var)
return;
printinfo(10)
printinfo(70,60,50)
Output
10
Output
70
60
50
2/22/2022 83
Karpagam Institute of Technology
84. 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 84
Karpagam Institute of Technology
85. 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 85
Karpagam Institute of Technology
86. 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(‘Circulationt’,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 86
Karpagam Institute of Technology
87. 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 87
Karpagam Institute of Technology
88. VIDEO TUTORIAL
S.No Topic Link
1 Interpreter and Interactive mode https://youtu.be/3lvgY5V8494
2 Operator and it's types with their
Precedence
https://youtu.be/ljaw6cUobtU
3 Circulate the value of n numbers
using slicing operator
https://youtu.be/1Y46EaJAQ4c
4 Distance between two points https://youtu.be/qeZ5kiKJe7c
2/22/2022 88
Karpagam Institute of Technology
89. 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 89
Karpagam Institute of Technology
90. ASSIGNMENT QUESTIONS
S.No Questions Blooms Level
1 Write a Python programs to check
whether the given number is palindrome
or not
K3
2 Apply the concept of Modules for airlines
system
K3
3 Distinguish between Interpreter mode and
Interactive mode
K4
4 Develop a Python program for finding
Fibonacci sequence of n numbers using
function with recursion
K5
2/22/2022 90
Karpagam Institute of Technology
91. QUIZ - TEST YOUR KNOWLEDGE
• https://forms.gle/uP745eEsYzko6Y2U9
2/22/2022 91
Karpagam Institute of Technology
92. UNIT III CONTROL FLOW, FUNCTIONS
SYLLABUS
Conditionals: Boolean values and operators, conditional (if),
alternative (if-else), chained conditional (if-elif-else);
Iteration: state, while, for, break, continue, pass; Fruitful
functions: return values, parameters, local and global scope,
function composition, recursion; Strings: string slices,
immutability, string functions and methods, string module;
Lists as arrays.
Illustrative programs: square root, gcd, exponentiation, sum
an array of numbers, linear search, binary search.
2/22/2022 92
Karpagam Insitute of Technology
2/22/2022 92
93. BOOLEAN EXPRESSION
A Boolean expression is a expression that results in either true
or false.
It uses the == operator which compares two operands and
procedures true if both are equal otherwise false.
93
Karpagam Institute of Technology
2/22/2022
94. CONTROL FLOW
• It is a statement that determines the control flow of a set of
instructions., (ie) it decides the sequence in which the
instructions in a program are to be executed.
• It can either comprise of one or more instructions. Three
fundamental control statements are
Sequential
Selection
Iterative control
94
Karpagam Institute of Technology
2/22/2022
95. TYPES OF DECISION CONTROL STATEMENTS
95
Karpagam Institute of Technology
2/22/2022
96. SELECTION OR CONDITIONAL BRANCHING
STATEMENT
• The decision control statements usually jumps from one part of
the code to another depending on whether a particular
condition is satisfied or not.
• Python selection statements are:
If statement
If-else statement
If-elif-else statement
Nested-if statement
96
Karpagam Institute of Technology
2/22/2022
97. ITERATIVE STATEMENTS
• Iterative statements are decision control statements that are
used to repeat the execution of a list of statements. The
following are the types of iterative statements.
while loop
for loop
97
Karpagam Institute of Technology
2/22/2022
98. WHILE LOOP
• The while loop provides a mechanism to repeat one or more
statements while a particular condition is true.
• Syntax:
Statement X
while (condition):
Statements block
98
Karpagam Institute of Technology
2/22/2022
100. EXAMPLE FOR WHILE LOOP
num = 1
while num < 10:
print(num)
num = num + 3
Ouput:
1
4
7
100
Karpagam Institute of Technology
2/22/2022
101. 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
101
Karpagam Institute of Technology
2/22/2022
102. FOR LOOP
• It provides a mechanism to repeat a task until a particular
condition is true.
• It is known as determinate or definite loop because the
programmer knows exactly how many times the loop will
repeat.
Syntax 1:
for loop_control_var in sequence:
Statement block
102
Karpagam Institute of Technology
2/22/2022
103. FOR LOOP CONTD..
Syntax 2:
for variable in range(beg,end,[step]):
Statements
103
Karpagam Institute of Technology
2/22/2022
104. FLOWCHART OF FOR LOOP
104
Karpagam Institute of Technology
2/22/2022
105. EXAMPLE OF FOR LOOP
numbers = [1, 2, 4, 6, 11, 20]
sq = 0
for val in numbers:
sq = val * val
print(sq)
105
Karpagam Institute of Technology
2/22/2022
Output:
1
4
16
36
121
400
106. 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
Karpagam Institute of Technology
2/22/2022
107. RANGE( ) IN FOR LOOP CONTD..
• range(start, stop, step_size): The default step_size is 1
which is why when we didn’t specify the step_size, the
numbers generated are having difference of 1. However
by specifying step_size we can generate numbers having
the difference of step_size.
For example:
range(1, 10, 2) is equivalent to [1, 3, 5, 7, 9]
107
Karpagam Institute of Technology
2/22/2022
108. EXAMPLE OF FOR LOOP WITH RANGE( )
sum = 0
for val in range(1, 6):
sum = sum + val
print(sum)
Output:
15
108
Karpagam Institute of Technology
2/22/2022
109. EXAMPLE OF FOR LOOP WITH ELSE BLOCK
for val in range(5):
print(val)
else:
print("The loop has completed execution")
Output:
0
1
2
3
4
The loop has completed execution
109
Karpagam Institute of Technology
2/22/2022
110. BREAK STATEMENT
• The break statement is used to terminate the
execution of the loop.
• When a compiler encounters a break statement, the
control passes to the statement that follows the loop
in which the break statement appears.
• Syntax:- break
110
Karpagam Institute of Technology
2/22/2022
111. FLOWCHART FOR BREAK STATEMENT
111
Karpagam Institute of Technology
2/22/2022
112. EXAMPLE FOR BREAK STATEMENT
# program to display all the elements before number 88
for num in [11, 9, 88, 10, 90, 3, 19]:
print(num)
if(num==88):
print("The number 88 is found")
print("Terminating the loop")
break
112
Karpagam Institute of Technology
2/22/2022
Output:-
11
9
88
The number 88 is found
Terminating the loop
113. CONTINUE STATEMENT
• The continue statement can only appear in the body
of a loop.
• When a compiler encounters a continue statement,
then the rest of the statement s in the loop are skipped
and the control is unconditionally transferred to the
loop-continuation portion of the nearest loop.
• Syntax: continue
113
Karpagam Institute of Technology
2/22/2022
115. EXAMPLE FOR CONTINUE STATEMENT
# program to display only odd numbers
for num in [20, 11, 9, 66, 4, 89, 44]:
if (num%2 == 0):
continue
print(num)
115
Karpagam Institute of Technology
2/22/2022
Output
11
9
89
116. PASS STATEMENT
• The pass statement acts as a placeholder and usually used
when there is no need of code but a statement is still required to
make a code syntactically correct.
• Example:-
for num in [20, 11, 9, 66, 4, 89, 44]:
if num%2 == 0:
pass
else:
print(num)
Output:
11
9
89
116
Karpagam Institute of Technology
2/22/2022
117. STRINGS
• String is a sequence of characters.
• String may contain alphabets, numbers and special
characters.
• String value must be enclosed within either single
quotes or within double quotes.
• String is immutable in nature. (i.e)., once created
cannot be able to edit when it is stored in a variable.
Example:
Letter = “A”
Name = ‘python’
117
Karpagam Institute of Technology
2/22/2022
118. READING STRING VALUE FROM THE USER:
• Using input( ) function we can read string value from
the user.
Syntax:
Variable_name=input(“Enter the values”)
Example:
Name=input(“Enter the name”)
print(“Welcome”,name)
Output:
Enter the name: python
Welcome python
118
Karpagam Institute of Technology
2/22/2022
119. INDEX OPERATION:
• Each character can be accessed through index operator.
Syntax:
String_variable_name[index]
• Index value starts at zero and last index value is(length of
the string-1)
Example:
119
Karpagam Institute of Technology
2/22/2022
121. CONCATENATION OF TWO OR MORE STRINGS
• Joining of two or more strings into a single one is
called concatenation.
Syntax: String2=string1+string2
Example:
str1 = 'Hello'
str2 ='World!'
print('str1 + str2 = ', str1 + str2)
Output:
Hello World!
121
Karpagam Institute of Technology
2/22/2022
122. REPETITION OPERATOR(*):
• It is used to concatenate the same string multiple
times.
Syntax:
String2=String1*integer value
Example:
str1 = 'Hello'
print('str1 * 3 =', str1 * 3)
Output:
HelloHelloHello
122
Karpagam Institute of Technology
2/22/2022
123. STRING SLICING
• Slicing operations is used to select/return /slice
the particular substring based on user
requirements.
• A segment of the string is called slice.
Syntax:
String_variable_name[start:end:step value]
• Here all the parameters/variables are optional
• The default value for start is zero and end is end-1
• The default value for step is 1.
123
Karpagam Institute of Technology
2/22/2022
124. 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
124
Karpagam Institute of Technology
2/22/2022
125. 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.
125
Karpagam Institute of Technology
2/22/2022
126. 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
Karpagam Institute of Technology
2/22/2022
Output:-
is both string are equal:False
is both string are not equal:True
is str1>str2:True
is str1>str2:False
127. STRING ITERATION:
• We can us for loop to traverse all the characters in the
string sequentially.
• Syntax1:
for var_name in string_varaible_name:
statements
• Syntax2:
for var_name in range(initial, final,step value):
statements
127
Karpagam Institute of Technology
2/22/2022
128. 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
128
Karpagam Institute of Technology
2/22/2022
129. 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
129
Karpagam Institute of Technology
2/22/2022
130. STRING IMMUTABILITY
• Strings are immutable in nature.
• We cannot edit the string value once it is assigned to variable.
• If we try to assign or replace a value in the string, it displays
an error message that str is not a mutable object.
Program:
str= “welcome”
print(str[3])
str[3]= “c”# assigning value c to index 3 place
print(str)
Output:
c
Traceback (most recent call last):
str[3]=”c’# assigning value c to index 3 place
TypeError:’str’ object does not support item assignment
130
Karpagam Institute of Technology
2/22/2022
131. STRING MODULES
• String modules contain a number of functions to
process standard python string.
• This can be done by importing string function.
Syntax:
import string
131
Karpagam Institute of Technology
2/22/2022
132. LIST AS ARRAY:
• Array is a collection of similar data items that are
stored under a common name.
• Python is not providing array data type rather than it
provides a LIST.
Implementing array in python one-dimensional list:
• Arrays can be implemented as one dimensional list.
• Ex: Price_list=[70,80,90,93.5,30.456]
132
Karpagam Institute of Technology
2/22/2022
133. MINIMUM VALUE IN THE LIST WITHOUT USING
INBUILT FUNCTION:
price_list=[70,80,90,93.5,30.456]
min=price_list[0]
for min_value in 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
133
Karpagam Institute of Technology
2/22/2022
134. 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 i in range(len(two_dim)):
for j in range(len(two_dim[i])):
print(two_dim[i][j],end=“”)
print(“n”)
134
Karpagam Institute of Technology
2/22/2022
135. SQUARE ROOT OFA 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--
135
Karpagam Institute of Technology
2/22/2022
136. 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 136
Karpagam Institute of Technology
137. 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))
137
Karpagam Institute of Technology
2/22/2022
138. 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
138
Karpagam Institute of Technology
2/22/2022
140. 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”)
140
Karpagam Institute of Technology
2/22/2022
141. VIDEO TUTORIAL
S.NO TOPIC LINK
1 Boolean Values and
Operators
https://youtu.be/7vy_GffZZTg
2 Loops in Python https://www.youtube.com/watch?v=
zFvoXxeoosI
3 Fruitful Functions https://youtu.be/hMGc19ZYzDM
4 Strings in Python https://www.youtube.com/watch?v=
QGLNQwfTO2w
5 Linear Search https://youtu.be/fHMXsGkN5cg
2/22/2022 141
Karpagam Institute of Technology
142. SUMMARY
• Python branching statements
• Python looping statements
• Strings and its methods.
• Illustrative Programs
2/22/2022 Karpagam Institute of Technology 142
143. ASSIGNMENT QUESTIONS
S.NO QUESTIONS BLOOMS LEVEL
1 Write a Python program to check whether a
given number is a perfect number
K3
2 Write a Python program to calculate the number
of words and number of characters present in a
string
K3
3 Write a Python code to count the occurrences of
each word in a given string sequence
K3
4 Develop a Python code to check whether a string
is palindrome or not
K5
5 Develop a Python program to detect whether
two strings are anagrams
K5
2/22/2022 143
Karpagam Institute of Technology
144. QUIZ-TEST YOUR KNOWLEDGE
• https://docs.google.com/forms/d/e/1FAIpQLSc
Yn1TS4wfhudU0CgVwuCGlEZPQmchmz1_l
av0Q2oiONI8Gbw/viewform
2/22/2022 Karpagam Institute of Technology 144