0% found this document useful (0 votes)
72 views153 pages

Python Unit II Unit 3 COntrol Flow FINAL

Uploaded by

Esther Priya R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views153 pages

Python Unit II Unit 3 COntrol Flow FINAL

Uploaded by

Esther Priya R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 153

GE8151 - PROBLEM SOLVING AND PYTHON

PROGRAMMING

Unit III – Control Flow, Functions

Problem Solving and Python Programming


Control Flow, Functions

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.

Problem Solving and Python Programming


Boolean Expression
A Boolean expression is an expression that is either true or false.
Example:
we can use the operator ==, which compares two operands and produces
True if they are equal and False otherwise,
>>> 5==5
True
>>> 5==6
False
True and False are special values that belong to the type bool; they are not
strings
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>

Problem Solving and Python Programming


Boolean Expression
The = = operator is one of the comparison operators; the others are
as follows,
x != y # x is not equal to y
x>y # x is greater than y
x<y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y

Remember that = is an assignment operator and == is a


comparison operator

Problem Solving and Python Programming


Operators
Python supports different types of operators which are as follows,
Arithmetic Operators,
Comparison(Relational) Operators,
Assignment Operators,
Logical Operators,
Unary Operators,
Bitwise Operators,
Membership Operators, and
Identity Operators.

Problem Solving and Python Programming


Arithmetic Operators

Operator Description

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus Division
Floor Division (It removes the digits after the
//
decimal point)
** Exponent

Problem Solving and Python Programming


Comparison Operators

Operator Description

== Checks Equality

!= Not Equal

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

Problem Solving and Python Programming


Assignment Operators
Operator Description

= Assigns Value

+= Add & Assign (a+=b is same as a=a+b)

-= Subtract & Assign

*= Multiply & Assign

/= Divide & Assign

%= Modulus & Assign

//= Floor Division

**= Exponent & Assign


Problem Solving and Python Programming
Unary Operators

It will act on single operand.


Python supports unary minus operator.
Unary minus operator is different from arithmetic operator where
it operates on two operands.
Unary operator negates the operands value
Example:
b=10
a= -(b)

Problem Solving and Python Programming


Shift Operators

Operator Description

<< Left Shift

>> Right Shift

Problem Solving and Python Programming


Logical Operators

Operator Description

&& Logical AND

|| Logical OR

! Logical NOT

Problem Solving and Python Programming


Membership Operators

Operator Description
Returns TRUE if a variable is found in the
in Operator
specified sequence and FALSE otherwise.
Returns TRUE if a variable is not found in
not in
the specified sequence and FALSE
Operator
otherwise

Problem Solving and Python Programming


Identity Operators

Operator Description
Returns TRUE if the operands of both side
is Operator of the operator point to the same object and
FALSE otherwise.
Returns TRUE if the operands of both side
is not
of the operator does not point to the same
Operator
object and FALSE otherwise

Problem Solving and Python Programming


Control Flow/Control Structure

Problem Solving and Python Programming


Control Flow/Statement
It decides the sequence in which the instructions in the program
are to be executed.
Control Statement: Determines the control flow of a set of
instructions (i.e.) decides the sequence in which the instructions in
a program are to be executed.

Three fundamental methods of control flow are as follows,


Sequential Statements,
Selection Statements, and
Iterative Statements.

Problem Solving and Python Programming


Selection/Decision/Conditional
Statements
 Decision making is required when we want to execute a code
only if a certain condition is satisfied.

Conditional Statements allows us to check conditions and


change the behavior of the program accordingly.

Types of Conditional Branching Statements,


IF Statement
IF-ELSE Statement
Nested IF Statement
IF-ELIF-ELSE Statement
Problem Solving and Python Programming
IF Statement

Syntax:
if(condition):
statement(s)

if 12 > 3:
print(“Twelve is greater !")

Problem Solving and Python Programming


IF Statement
Syntax:
if(condition):
statement(s)

Example:
x=10
if(x>0):
x=x+1
print(“x=”,x)
x=11

Problem Solving and Python Programming


IF Statement
Program to determine whether a person is eligible to Vote

age=int(input(“Enter the Age:”))


if(age>=18):
print(“You are eligible to Vote”)

Enter the Age: 30


You are eligible to Vote

Problem Solving and Python Programming


IF-ELSE Statement

Syntax:
if(condition):
Statement Block 1
else:
Statement Block 2

If condition is TRUE then Statement Block 1 will be executed


and Statement Block 2 will be skipped.
Otherwise, if condition is FALSE then Statement Block 2 will be
executed and Statement Block 1 will be skipped

Problem Solving and Python Programming


IF-ELSE Statement
Program to determine whether a person is eligible to Vote

age=int(input(“Enter the age:”))


if(age>=18)
print(“You are eligible to Vote”)
else:
print(“You are not eligible to vote”)
Output:
Enter the age: 25
You are eligible to Vote

Problem Solving and Python Programming


IF-ELIF-ELSE Statement (Chained)
Sometimes there are more than two possibilities and we need
more than two branches.
Syntax:
if(condition1):
Example:
statement block 1
if x < y: elif(condition 2):
print 'x is less than y' statement block 2
……………………..
elif x > y: elif(condition n):
print 'x is greater than y' statment block N
else: else:
statement block X
print 'x and y are equal' Statement Y

Problem Solving and Python Programming


IF-ELIF-ELSE Statement (Chained)
elif is an abbreviation of “else if.” Again, exactly one branch will
be executed. There is no limit on the number of elif statements.
If there is an else clause, it has to be at the end, but there doesn’t
have to be one.
Example:
if choice == 'a':
draw_a()
elif choice == 'b':
draw_b()
elif choice == 'c':
draw_c()

Problem Solving and Python Programming


IF-ELIF-ELSE Statement (Chained)
Each condition is checked in order.
If the first is false, the next is checked, and so on.
If one of them is true, the corresponding branch executes, and the
statement ends.
Even if more than one condition is true, only the first true branch
executes.

Problem Solving and Python Programming


IF-ELIF-ELSE Statement (Chained)
Program to check whether the character is vowel or not

ch=input(“Enter any Character:”)


if(ch==“A” || ch==“E” || ch==“I” || ch==“O” || ch==“U”)
print(ch,”is a Vowel”)
elif(ch==“a” || ch==“e” || ch==“i” || ch==“o” || ch==“u”)
print(ch,”is a Vowel”)
else:
print(ch,”is not a Vowel”)
Output:
Enter any Character: h
h is not a Vowel

Problem Solving and Python Programming


IF-ELIF-ELSE Statement (Chained)
Program to check whether the character is vowel or not

ch=input(“Enter any Character:”)


if ch in (“A”,“E”,“I”,“O”,“U”,“a”,“e”,“i”,“o”,“u”)
print(ch,”is a Vowel”)
else:
print(ch,”is not a Vowel”)
Output:
Enter any Character: h
h is not a Vowel

Problem Solving and Python Programming


Iterative Statements
Iterative Statements are decision control statements that are used
to repeat the execution of a list of statements.
Python supports two types of Iterative Statements,
while loop, and
for loop

Problem Solving and Python Programming


while Loop
Repeat one or more statements while the particular condition is
true.
Syntax:

while (condition):
statement(s)

In while loop, the condition is tested before any of the statements
in the statement block is executed.
If the condition is true then the statement block will executed
otherwise, the control will jump to statement Y

Problem Solving and Python Programming


while Loop

The while loop will execute as long as the condition is True.

Suppose if the condition is never updated and the condition never


becomes false, then the loop becomes infinite.
While loop is also refereed as top-checking loop or entry
controlled loop since the control condition is placed as the first
line of the code.
If the control condition evaluated false, then the statement
enclosed in the loop are never executed.

Problem Solving and Python Programming


While loop
Checks the condition each time before executing the
statements in the body of loop.
Print first 5 natural numbers
i=1
while(i<=5):
print(i)
i=i+1

Output:
1
2
3
4
5
JanuaryProblem
4, 2025 Solving and Python Programming
while Loop

Example: Print first 10 numbers


i=1
while(i<=10):
print(i, end=“ “)
i=i+1
print(“Completed”)
Output:
1 2 3 4 5 6 7 8 9 10 Completed

Problem Solving and Python Programming


while Loop

Example: Print first 10 numbers Example: Sum of first 10 numbers


i=1
i=1 sum=0
while(i<=10): while(i<=10):
print(i, end=“ “) sum=sum+i
print(i, end=" ")
i=i+1
i=i+1
print(“Completed”)
print("Completed")
print("Sum=",sum)

Output:
0 1 2 3 4 5 6 7 8 9 10 Completed
Sum= 55
Problem Solving and Python Programming
while Loop
Example: Sum and Average of first 10 Numbers
i=0
s=0
while(i<=10):
s=s+i
i=i+1
avg=float(s)/10
print(“The Sum of first 10 Numbers is:”,s)
print(“The average of first 10 Numbers is:”, avg)

Output:
The Sum of first 10 Numbers is: 55
The average of first 10 Numbers is: 5.5

Problem Solving and Python Programming


Question!!
How many times will the loop run?

i=2

while(i>0):

i=i-1 Options:
A. 2
B. 3
C. 1
D. 0

Problem Solving and Python Programming


For loop

for loop also provides the mechanism to repeat a task until a particular
condition is True.
It is usually known as a definite loop because the programmer knows how
many times the loop will repeat.
In python, for…in is a statement used to iterate over the sequence of
statements.

Every iteration the loop must make the loop control variable closer to the
end of the range (i.e.) the loop control variable will be updated for every
iteration.

Problem Solving and Python Programming


For loop

Repeats execution of a sequence of statements for a specific


number of times.

OUTPUT:
1
2
Sita
7
Ram
5
JanuaryProblem
4, 2025 Solving and Python Programming
For loop

Repeats execution of a sequence of statements for a specific


number of times.
list=[1,2,’Sita’,7,’Ram’,5]
for counter in list:
print(counter)

OUTPUT:
1
2
Sita
7
Ram
5
JanuaryProblem
4, 2025 Solving and Python Programming
Loop Control Statements

Are used to change the flow of execution from its normal


sequence.
 Break
 Continue
 Pass

JanuaryProblem
4, 2025 Solving and Python Programming
The break Statement

To break out from a loop, use the keyword “break”


Syntax:
break

list=[1,2,’Sita’,7,’Ram’,5] OUTPUT:
for counter in list: 1
print(counter) 2
if counter == 7: Sita
break 7

Problem Solving and Python Programming


The break Statement

It is used to terminate the execution of the nearest enclosing loop which
it appears.
It is widely used in for and while loop.

When compiler encounters a break statement, it terminates the loop and


transfers execution to the statement immediately following the loop.
Break statement is used to exit a loop at any point within its body.

Problem Solving and Python Programming


The break Statement
Syntax:
while…

if(condition):
break


transfers the control out of while loop

Problem Solving and Python Programming


The break Statement
Syntax:
for…

if(condition):
break


transfers the control out of for loop

Problem Solving and Python Programming


The break Statement
Syntax:
for…

for…

if(condition):
break


transfers the control out of inner for loop

Problem Solving and Python Programming


Question

i=1
while i<=10:
print(i, end=“ “)
if(i==5):
break
i=i+1
print(“Completed”)
Output:
12345
Completed

Problem Solving and Python Programming


The continue Statement
With the continue statement we can stop the current
iteration of the loop, and continue with the next
Syntax:
continue

OUTPUT:
list=[1,2,’Sita’,7,’Ram’,5] 1
for counter in list: 2
if counter == 7: Sita
continue Ram
print(counter) 5

Problem Solving and Python Programming


The continue Statement
Like break statement, continue statement only appear in the body of a
loop.
When a compiler encounters a continue statement, the rest of the
statements in the loop are skipped and the control is unconditionally
transferred to the loop continuation portion of the nearest enclosing loop.

When a continue statement is used in while loop, the control is


transferred to the code that test the controlling expression.
When a continue statement is used in for loop, the control is transferred
to the code that updates the loop variable.
continue statement is used to stop the current iteration of the loop and
continues with the next one

Problem Solving and Python Programming


The continue Statement
Syntax:
while(…)

if(condition):
continue


for(…)
for(…)

if(condition):
continue

Problem Solving and Python Programming


Question
continue Statement
for i in range(1, 11)
if(i==5)
continue
print(i, end=“ “)
print(“COMPLETED”)

Output:
1 2 3 4 6 7 8 9 10
COMPLETED

Problem Solving and Python Programming


Question

import math What is the output


while(1): of the program, if
num=int(input("Enter the Number:")) num takes the value
if(num==999): 25?
break
elif(num<0):
print("Square of Negative Numbers cannot be
calculated")
else:
print("Square Root of",num,"=",math.sqrt(num))

Problem Solving and Python Programming


Answer
Output:
Enter the Number:25
Square Root of 25 = 5.0

Enter the Number:50


Square Root of 50 = 7.0710678118654755

Enter the Number:-1


Square of Negative Numbers cannot be calculated

Enter the Number:999

Problem Solving and Python Programming


The pass Statement
Pass is used when a statement is required syntactically but no command
or code has to be executed.
It specifies simple a NULL operation.
Syntax:
pass

Problem Solving and Python Programming


The pass Statement
Pass is used when a statement is required syntactically but no command
or code has to be executed.
It specifies simple a NULL operation.
Syntax:
pass
pass statement can be written because, we cannot have as empty body of
the loop.
Though pass statement will not do anything but it will make the program
syntactically correct.
pass statement can be used when we have a loop that is not implemented
yet, but we may wish to write some code in it in the future.

Problem Solving and Python Programming


The pass Statement

>>> for counter in list:

Output:
Produces Error - KeyboardInterrupt

>>>for counter in list:


pass

Output:
Above statement will execute

Problem Solving and Python Programming


Iterative Statements - pass

• pass statement is never executed.


• Behaves like a placeholder for future code.
def display(number):

if number is 2:
pass
else:
print ("Number: ", number)

display(2)
Output:
display(3)
???

JanuaryProblem
4, 2025 Solving and Python Programming
Iterative Statements - pass

• pass statement is never executed.


• Behaves like a placeholder for future code.
def display(number):

if number is 2:
pass
else:
print ("Number: ", number)

display(2)
Output:
display(3)
Number: 3

JanuaryProblem
4, 2025 Solving and Python Programming
The pass Statement
In python programming, pass is a NULL statement.
Difference between pass & comment is that while the interpreter ignores
a comment entirely, but pass is not ignored.
comment statement will not get executed but the pass statement will be
executed but nothing happens.

Difference between break, continue & pass statements.

Problem Solving and Python Programming


Loop Control Statements

Are used to change the flow of execution from its normal


sequence.
 Break - Terminates the execution of loop statements
 Continue - Stops the current iteration of the loop, and

continue with the next


 Pass - is a NULL statement. Used when a statement is
required by Python syntax, but no action is required. i.e.,It
is used where we cannot have as empty body of the
loop/function
JanuaryProblem
4, 2025 Solving and Python Programming
For loop – range function

It is a built-in function in python that is used to iterate over


the sequence of numbers.

Here first and third parameter is an optional, by default every


argument in range is incremented by 1

JanuaryProblem
4, 2025 Solving and Python Programming
for Loop
range() function:
With single argument:
Example: range(10) is equal to range(0,10)

With two argument:


Example: range(0,10) it produces values from 0 to 9

With three arguments:


Example: Third argument specifies the interval of sequence
produced.

Problem Solving and Python Programming


for Loop
Example:
for i in range(1,5):
print(i)

Output:
1
2
3
4

Problem Solving and Python Programming


for Loop
Example:
for i in range(1,5):
print(i, end=“ ”)

Output:
1234

Problem Solving and Python Programming


for Loop
Example:
for i in range(1,5):
print(i, end=“ “)

Output:
1234

Example:
for i in range(1,10,2):
print(i, end=“ “)
Output:
13579

Problem Solving and Python Programming


for loop – range function

Iterate over a specific number of times within a given range in


steps/intervals mentioned.

????

JanuaryProblem
4, 2025 Solving and Python Programming
for loop – range function

Iterate over a specific number of times within a given range in


steps/intervals mentioned.

JanuaryProblem
4, 2025 Solving and Python Programming
for loop – range function

Iterate over a specific number of times within a given range in


steps/intervals mentioned.

for i in range (1,10,3):


Output:
print(i, end=“ ”) ???

JanuaryProblem
4, 2025 Solving and Python Programming
for loop – range function

Iterate over a specific number of times within a given range in


steps/intervals mentioned.

for i in range (1,10,3):


Output:
print(i, end=“ ”) 1 4 7

JanuaryProblem
4, 2025 Solving and Python Programming
for loop – range function

Iterate over a specific number of times within a given range in


steps/intervals mentioned.

for i in range (1,10,-2):


Output:
print(i, end=“ ”) ???

JanuaryProblem
4, 2025 Solving and Python Programming
for loop – range function

Iterate over a specific number of times within a given range in


steps/intervals mentioned.

for i in range (1,10,-2):


Output:
print(i, end=“ ”) No Output

JanuaryProblem
4, 2025 Solving and Python Programming
Nested loop

a=["red","tasty"]
b=["apple","cherry"]
for x in a:
for y in b:
print(x,y) Output:
red apple
red cherry
tasty apple
tasty cherry

JanuaryProblem
4, 2025 Solving and Python Programming
Factorial of a given number using loop

num=int(input(“Enter the Number:”))


fact=1
for i in range(1,num+1)
fact=fact*i
print(“Factorial of”,num,”is:”,fact)

Output:
Enter the number: 5
Factorial of 5 is: 120

Problem Solving and Python Programming


Fruitful Functions

Problem Solving and Python Programming


Fruitful Functions

 A fruitful function is one in which there is a return


statement with an expression.
 Most of the built in functions that we have used are
fruitful.
Example:
>>> abs(- 42)
42

Problem Solving and Python Programming


Fruitful Functions

 A fruitful function is one in which there is a return


statement with an expression.
 Most of the built in functions that we have used are
fruitful.
Example:
>>>biggest=max(3,7,2,5)
>>>biggest
7

Problem Solving and Python Programming


Fruitful Functions
User defined function - Return Values
Consider an example for calculating an Area of Circle
def area(radius):
temp = 3.14159 * radius**2
return temp
area(3)

Output: 28.27431

Problem Solving and Python Programming


Fruitful Functions
User defined function - Return Values
Consider an example for calculating an Area of Circle
def area(radius):
temp = 3.14159 * radius**2
return temp
area(3)

Output: 28.27431

We could have written this function more concisely as,


def area(radius):
return math.pi * radius**2
area(3)
Output: 28.27431
Problem Solving and Python Programming
Fruitful Functions
User defined function - Return Values
Code that appears after a return statement, or any other place the flow of
execution can never reach, is called dead code.
In a fruitful function, it is a good idea to ensure that every possible path
through the program hits a return statement.
Example:
def absolute_value(x):
This function is incorrect
if x < 0:
since it returns the value
return -x None when x happens to
if x > 0: be 0
return x

print(absolute_value(-7))

Problem Solving and Python Programming


Fruitful Functions – Return Values

def cube(x):
z=x*x*x
return(z)

num=10
result=cube(num)
print("Cube of",num,"=",result)
--------------------------------------
Output:
Cube of 10 = 1000

Problem Solving and Python Programming


Fruitful Functions – Return Values

def cube(x): def cube(x):


z=x*x*x return (x*x*x)
return(z)
num=10
num=10 result=cube(num)
result=cube(num) print("Cube of",num,"=",result)
print("Cube of",num,"=",result)
--------------------------------------
Output:
Cube of 10 = 1000

Problem Solving and Python Programming


Variable Scope & Lifetime

In python, we cannot access any variable from any part of the
program.
Existence of the variable depends on how the variable has been
declared.

Terminologies are as follows,


Scope of the Variable: Specifies the part of the program in
which the variable is accessible.
Lifetime of the Variable: Duration in which the variable Exist.

Problem Solving and Python Programming


Local & Global Variables

Local Variable:
A variable which is defined within a function is local to that
function.
In this program, there are 3
def add(x,y): local variables – x,y and sum.
sum = x + y
return sum

print(add(5, 10)) Output:15

Problem Solving and Python Programming


Local & Global Variables
Global variables are those variables which are declared outside of the
function or in global scope. This means that a global variable can be
accessed inside or outside of the function.

z = 25
def func():
print(z)

func()
print(z)

Output:
25
25

Problem Solving and Python Programming


Local & Global Variables
Global variables are those variables which are declared outside of the
function or in global scope. This means that a global variable can be
accessed inside or outside of the function.

z = 25 z = 25
def func(): def func():
print(z) z=10
print(z)
func()
print(z) func()
print(z)
Output: Output:
25 10
25 25
Problem Solving and Python Programming
Local & Global Variables
Global variables are those variables which are declared outside of the
function or in global scope. This means that a global variable can be
accessed inside or outside of the function.

z = 25 z = 25 z = 25
def func(): def func(): def func():
print(z) z=10 global z
print(z) z=10
func() print(z)
print(z) func()
print(z) func()
Output: Output: print(z) Output:
25 10 10
25 25 10
Problem Solving and Python Programming
Here is a Question

What is the output of below code?

def func():
print(z)
z=36
print(z)

z=10
func()
print(z)
Output: ???

Problem Solving and Python Programming


Here is a Question

What is the output of below code?

def func():
print(z)
z=36
print(z)

z=10
func()
print(z)
Output:
UnboundLocalError: local variable 'z'
referenced before assignment
Problem Solving and Python Programming
Here is a Question

What is the output of below code?


def func():
def func():
global z
print(z)
print(z)
z=36
z=36
print(z)
print(z)
z=10
z=10
func()
func()
print(z) Output:
print(z)
10
Output: 36
UnboundLocalError: local variable 'z' 36
referenced before assignment
Problem Solving and Python Programming
Here is a Question

What is the output of below code?


def func(): def func():
def func():
global z global z
print(z)
print(z) print(z)
z=36
z=36 z=36
print(z)
print(z) print(z)
z=10
z=10 z=10
func()
func() func()
print(z) Output: Output:
print(z) z=18
10 10
Output: 36 print(z) 36
UnboundLocalError: local variable 'z' 36 18
referenced before assignment
Problem Solving and Python Programming
Local & Global Variables

Global Variable Local Variable


They are defined in the main They are defined within a
body of the program function
They can be accessed They can be accessed only
throughout the program within that particular function

Global variables are accessible Local variables are not related


to all functions of the program. in any way to other variables
with the same name used
outside the function

Problem Solving and Python Programming


Using Global Statement
Example:

Problem Solving and Python Programming


Local & Global Variables
We can have a variable with the same name as that of a global variable
in the program.
Example:
var=“Good”
def show():
var=“Morning”
print(“In Function var is - ”, var)
show()
print(“Outside Function Var is - ”, var)
Output:
In Function var is - Morning
Outside Function Var is - Good

Problem Solving and Python Programming


Local & Global Variables
If we have a Global Variable and then create another variable using the
Global Statement, then changes made in the variable will be reflected
everywhere in the program.
Example:
var=“Good”
def show()
global var
var=“Morning”
print(“In Function var is - ”, var)
show()
print(“Outside Function var is - ”,var)
var=“fantastic”
print(“Outside function after modification var is - ”, var)

Problem Solving and Python Programming


Local & Global Variables
Output:
In Function var is – Morning
Outside Function var is – Morning
Outside function after modification var is - Fantastic

Problem Solving and Python Programming


Resolution of Names
All names assigned inside a function def statement are locals
by default; functions can use globals, but they must declare
global to change them.
Python’s name resolution is sometimes called the LGB rule,
after the scope names:

When you use an unqualified name inside a function, Python


searches three scopes—the local (L), then the global (G), and
then the built-in (B)—and stops at the first place the name is
found.

Problem Solving and Python Programming


Resolution of Names
Example:

 In the code given, str is a global string because it has been


defined before calling the function.

Problem Solving and Python Programming


Resolution of Names
Example: Example:
def func(): def func():
print(str) global str
print(str)
str=“Hello World”
str=“Hello World”
print(str) print(str)
str=“Welcome to Python” str=“Welcome to Python”
func() func()

Output: Output:
Local variable ‘str’ referenced Welcome to Python
before assignment Hello World

Problem Solving and Python Programming


Function Composition

Function Composition combines two functions in


such a way that the result of one function is passed as an
argument to the other function.

It is denoted as f(g(x)) where, x is an argument to the


function g() and the result of g(x) is an argument to the
function f()

Problem Solving and Python Programming


Function Composition

Computes the area of the circle


Assume xc and yc  center point; xp and yp  perimeter point.
First step: Find the radius of the circle, which is the distance between the
two points.
We just wrote a function, distance, that does,
radius = distance(xc, yc, xp, yp)

Next step: Find the area of a circle with that radius;


result = area_of_circle(radius)

Problem Solving and Python Programming


Function Composition

Computes the area of the circle


Assume xc and yc  center point; xp and yp  perimeter point.
First step: Find the radius of the circle, which is the distance between the
two points.
We just wrote a function, distance, that does,
radius = distance(xc, yc, xp, yp)

Next step: Find the area of a circle with that radius;


result = area_of_circle(radius)

• We can make it more concise by composing the function calls as shown


below
area_of_circle(distance(xc, yc, xp, yp))
Problem Solving and Python Programming
Function Composition
import math
def distance(x1,y1,x2,y2):
dist = math.sqrt((x2-x1)**2+(y2-y1)**2)
d=dist
return d
def area_of_circle(radius):
area=math.pi*radius*radius
return area
x1=int(input(" the value of x1 is"))
x2=int(input(" the value of x2 is"))
y1=int(input(" the value of y1 is"))
y2=int(input(" the value of y2 is"))
print(area_of_circle(distance(x1,x2,y1,y2)))
Problem Solving and Python Programming
Calculate factorial of a given number

Output:
Enter the number: 5
Factorial of 5 is: 120

Problem Solving and Python Programming


Example - To find the factorial of a
Number

Logic:

Output:
Enter the number: 5
Factorial of 5 is: 120

Problem Solving and Python Programming


Recursion
 It is a technique for solving a problem by breaking it down
into smaller sub-problem.
 Recursion involves a function, that calls itself until a
specified condition is met

Problem Solving and Python Programming


Recursion
 Every recursive solution has two major cases. They are:
 Base Case: Here the problem is simple enough to solve directly
without making any further calls to the same function
 Recursive Case:
 Problem is divided in to smaller sub problem
 Function calls itself with sub problem

 Result can be achieved by combing the solution of all sub problems

Problem Solving and Python Programming


Recursion - To find the factorial of a
Number
Algorithm
 STEP 1: Start
 STEP 2: Input N
 STEP 3: Call factorial(n)
f = n * factorial(n - 1)
 STEP 4: End
1 step
f = 5 * fact(4) = 120
factorial(n) 2 step
f = 4 * fact(3) = 24
 STEP 1: Set f=1 3 step
f = 3 * fact(2) = 6
 STEP 2: IF n==1 then return 1
4 step
ELSE f = 2 * fact(1) = 2
Set f=n*factorial(n-1) 5 step
n = 1; return 1
 STEP 3: Print f

Problem Solving and Python Programming


Recursion – Program Sample using Python

def factorial(n): #function definition


if n == 1:
return 1
else:
return n*factorial(n-1) #recursive function call

num = int(input("Enter a number: "))


if(num==0):
print(“1”)
else:
print("The factorial of",num,"is",factorial(num))
#function call

Problem Solving and Python Programming


Strings

Problem Solving and Python Programming


Strings
It is a Datatype.
It consist of a Sequence of characters.
Character could be a letter, digit, whitespace or any other symbol.
Python treats String as series of character delimited by single, double or
even triple quotes.

Example:
>>> message = ‘hello‘

Index of first character is 0 and the last character is n-1

>>> letter = message[1]

Problem Solving and Python Programming


Strings as sequences

• String: sequence or list of characters


• Positions 0,1,2,……..n-1 for a string of length n

• Position -1,-2 ……….. Counts backward from end

Problem Solving and Python Programming


String Slices

• A slice is a segment of a string


• The slice s[start:end] is the elements beginning at start
and extending up to but not including end.
>>> a = "helloworld"
>>> a[1]
'e‘
>>> a[1:5]
"ello"

• If we omit the first index (before the colon), the slice


starts at the beginning of the string.
>>> a[:5]
"hello"
Problem Solving and Python Programming
• If we omit the second index, the slice goes to the end of the
string.
>>> a[5:]
"world“
>>> a[-2] a = "helloworld"
'l'
>>> a[-2:]
'ld'
>>> a[:-2]
'hellowor‘
a[:: n] or a[::-n]= It works by doing [begin:end:step]
>>> a[::-1]
'dlrowolleh‘
>>> a[::1]
‘helloworld’

Problem Solving and Python Programming


Traversing a String

A String can be traversed by accessing character(s) from one index to another.


Traversal can be achieved either by using, while loop or for loop

Example:
message=“Hello”
for i in message:
print(i)

Output:
H
e
l
l
o
Problem Solving and Python Programming
Strings Are Immutable
• Which means one can’t change an existing string.
>>> a='hello'
>>> a[0]=‘c‘
• TypeError: 'str' object does not support item assignment

Problem Solving and Python Programming


Strings Are Immutable
• Which means one can’t change an existing string.
>>> a='hello'
>>> a[0]=‘c‘
• TypeError: 'str' object does not support item assignment
• Solution: Create a new string (i.e) a variation on the original
string:
>>> a=‘c’+a[1:]
>>> print(a)
cello

Problem Solving and Python Programming


Operations on strings

• Combine two strings: concatenation, operator +


>>> s='hello'
>>> t='world‘

>>> s+t
'helloworld‘

>>> t=' world'


>>> s+t
'hello world'

Problem Solving and Python Programming


Operations on strings

• Multiplication operator (*) creates a new string that


concatenates a string with itself some number of
times
>>> s=s*5
>>> print(s)
'hellohellohellohellohello'

Problem Solving and Python Programming


Operations on strings

• String comparison: compares based on the ascii value


(a=97……. Z=122 and A=65…… Z=90)
>>> 'hai'=='hello'
False
>>> 'hai'=='hai'
True
>>> 'hai'<='hello'
True
• Similarly other operations can also be used for comparison

Problem Solving and Python Programming


• Length of a string can be found using built-in function len.
>>> len(“hai")
3
• The in & not in operator can be used to check if a string is
present or not in another string.
>>> 'hell' in 'hello'
True
>>> 'full' in 'hello'
False

>>> 'hell' not in 'hello'


False
>>> 'full' not in 'hello'
True

Problem Solving and Python Programming


Built-in String Methods
Function Description Example
>>> message="hello world"
capitalize() Capitalize first letter of a String >>> print(message.capitalize())
Hello world

>>> message="hello world"


title() Returns String in a title case >>> print(message.title())
Hello World

>>> message=“Hello"
Converts all character in the
lower() >>> print(message.lower())
string to lowercase
hello

>>> message=“Hello"
Converts all character in the
upper() >>> print(message.upper())
string to uppercase
HELLO
Problem Solving and Python Programming
Strings Functions & Methods
Function Description Example
Toggles the case of every character. >>> message="how ARE you?"
swapcase() (uppercase to lower case and vice >>> print(message.swapcase())
versa) HOW are YOU?
Returns TRUE if the string contains
>>> message=“ HELLO”
atleast 1 character and every
isupper() >>> print(message.isupper())
character is an upper case alphabet
True
and FALSE otherwise
>>> message="hello"
Returns TRUE if the string has >>> print(message.islower())
atleast 1 character and every True
islower()
character is a lowercase alphabet or >>> message="helloH"
otherwise. >>> print(message.islower())
False

Problem Solving and Python Programming


Strings Functions & Methods
Function Description Example
>>> message="hello"
>>> print(message.isalpha())
Returns TRUE if string has atleast 1
True
isalpha() character and every character is an
>>> message="hello123"
alphabet and FALSE otherwise
>>> print(message.isalpha())
False
>>> message="123456"
>>> print(message.isdigit())
Returns TRUE if the string contains True
isdigit()
only digits. >>> message="123456H"
>>> print(message.isdigit())
False
>>> message="hello"
Returns TRUE if string has atleast 1 >>> print(message.isalnum())
character and every character is True
isalnum()
either a number or an alphabet and >>> message="hello!"
FALSE otherwise >>> print(message.isalnum())
False
Problem Solving and Python Programming
Strings Functions & Methods
Function Description Example
Checks if the string >>> message="hello"
ends with suffix. >>> print(message.endswith('he',0,len(message)))
endswith(suffix,
Returns TRUE if so False
beg, end)
and FALSE >>> print(message.endswith('lo',0,len(message)))
otherwise. True
Checks if the string
ends with prefix. >>> message="hello“
startswith(prefix,
Returns TRUE if so >>> print(message.startswith('ll',2,len(message)))
beg, end)
and FALSE True
otherwise.

Problem Solving and Python Programming


Built-in String Methods

Function Description Example


Returns string with original
string centered to a total of >>> string="hello"
center(width,
width columns and filled with >>> print(string.center(10,'*'))
fillchar)
fillchar in the columns that do **hello***
not have characters
Returns String left justified to a
total width columns. Columns >>> message="hello"
ljust(width,
without characters are padded >>> print(message.ljust(15,'*'))
[fillcharacter])
with the character specified in hello**********
the fillchar argument.
Returns String right justified to
a total width columns. Columns >>> message="hello"
rjust(width,
without characters are padded >>> print(message.rjust(15,'*'))
[fillchar])
with the character specified in **********hello
the fillchar argument.

Problem Solving and Python Programming


Strings Functions & Methods
Function Description Example
>>> message=“ Hello "
Removes all leading & trailing
strip() >>> print(message.strip())
white spaces in string
‘Hello’
>>> message=“ Hello "
Removes all leading white
lstrip() >>> print(message.lstrip())
spaces in string
‘Hello ‘
>>> message=“Hello"
Returns the highest alphabetical
max(str) >>> print(max(message))
character from the string str
o
>>> message=“Hello"
Returns the lowest alphabetical
min(str) >>> print(max(message))
character from the string str
H
>>> message="hi hi"
Replace all occurrences of old in
replace(old, new) >>> print(message.replace("h","o"))
a string with new
oi oi

Problem Solving and Python Programming


Strings Functions & Methods
Function Description Example
Checks if str is
present in the string.
>>> message="hello"
If found it returns
find(str,beg,end) >>> print(message.find("el",0,len(message)))
the position at which
1
str occurs, otherwise
returns -1.
Same as find but >>> message="How are you?“
rfind(str,beg,end) starts searching from >>> print(message.rfind("are",0,len(message)))
the end 4
Same as find but >>> message="hello"
index(str,beg,eng) raises an exception if >>> print(message.index("hi",0,len(message)))
str not found ValueError: substring not found
Same as index but >>> message="How are you?“
rindex(str,beg,end) start searching from >>> print(message.rindex("are",0,len(message)))
an end. 4

Problem Solving and Python Programming


Strings Functions & Methods
Function Description Example
Returns a list of substrings
separated by the specified >>> message="how,are,you?"
split(delim) delimiter. If no delimiter is >>> print(message.split(","))
specified then by default it split ['how', 'are', 'you?']
strings on all white spaces.
It joins a list of strings using the
>>> print('*'.join(['abc','def','ghi']))
join(list) delimiter with which the function
abc*def*ghi
is invoked
>>> message="hello"
Returns an enumerate object that
>>> print(list(enumerate(message)))
enumerate(str) lists the index and value of all
[(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4,
character in the string.
'o')]

Problem Solving and Python Programming


Strings Functions & Methods
Function Description Example
Returns TRUE if the string contains >>> message=“ "
isspace() only whitespace character and >>> print(message.isspace())
FALSE otherwise True
>>> message=“Hello"
Returns TRUE if the string is a valid
isidentifier() >>> print(message.isidentifier())
identifier
True
>>> str="he"
>>>
Counts number of times str occurs in
count(str, beg, message="helloworldhellohello"
a string. We can also specify the
end) >>> print(message.count(str, 0,
length using beg&end parameters.
len(message)))
3
Returns string left padded with zeros >>> message="1234"
zfill(width) to a total of width characters. It is >>> print(message.zfill(5))
used with numbers. 01234

Problem Solving and Python Programming


Strings Modules
String Module consist of a number of useful constants, classes and
functions.
These functions are used to manipulate strings.
To see the content of string module, we can use dir() with the module
name as the argument as shown below,
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode',
'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal',
'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip',
'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Problem Solving and Python Programming


Strings Modules
String Constants: Some constants defined in the string module as
follows,
Constants Description Example
>>>print(string.ascii_letters)
Refers the combination of
abcdefghijklmnopqrstuvwxyzAB
string.ascii_letters asci_uppercase and asci_lowercase
CDEFGHIJKLMNOPQRSTUV
constants
WXYZ

string.ascii_lower Refers to all Lowercase letters >>> print(string.ascii_lowercase)


case form a-z abcdefghijklmnopqrstuvwxyz

>>> print(string.ascii_uppercase)
string.ascii_upper Refers to all Uppercase letters
ABCDEFGHIJKLMNOPQRSTU
case form A-Z
VWXYZ

Problem Solving and Python Programming


Strings Modules
Constants Description Example
>>> print(string.digits)
string.digits Refers digits from 0-9
0123456789

Refers to hexadecimal digits, 0-9, >>> print(string.hexdigits)


string.hexdigits
a-f, A-F 0123456789abcdefABCDEF

>>> print(string.punctuation)
String of ASCII characters that are
string.punctuation !"#$%&'()*+,-./:;<=>?
considered to be punctuation
@[\]^_`{|}~

>>> print(string.printable)
0123456789abcdefghijklmnopqrst
Refers to a string of printable
uvwxyzABCDEFGHIJKLMNOP
characters which includes digits,
sring.printable QRSTUVWXYZ!"#$
letters, punctuation and
%&'()*+,-./:;<=>?@[\]^_`{|}~
whitespaces.

Problem Solving and Python Programming


List as Arrays
In programming, Array is a collection of elements of the same data type.
Arrays are popular in most programming languages like: Java, C/C++ &
JAVA.
But in Python, they are not that common most often we will be using
Lists in python.
We can treat lists as arrays. However, we cannot constraint the type of
elements stored in a list.
If we create arrays using array module, all elements of the array must be
of the same numeric type.

Problem Solving and Python Programming


List as Arrays
Creating an Array:
we need to import array module to create arrays as shown below,

import array as arr


a = arr.array('d', [1.1, 3.5, 4.5])
print(a)

Here, we created an array of float type. The letter ‘d’ is a type


code which determines the type of the array during creation.

Problem Solving and Python Programming


List as Arrays
Commonly used type codes as follows:

Type Code Python Type


i Integer
f Floating Point
d Double
u Character

Example:
Example:
import array as arr import array as arr
a = arr.array('i', [2, 4, 6, 8]) a = arr.array(‘u', [‘a’, ‘b’, ‘c’])
print(a) print(a)

Problem Solving and Python Programming


List as Arrays
Accessing an Element in an Array:
We use index to access elements of an array as shown below,

import array as arr


a = arr.array('u', ['a','b','c'])
print("First Element:",a[0])
print("First Element:",a[1])
print("First Element:",a[2])

Output:
First Element: a
First Element: b
First Element: c

Problem Solving and Python Programming


List as Arrays
Slicing an Array:
We can access a range of items in an array by using the slicing
operator ‘:’ as follows,

import array as arr


numbers_list = [2, 5, 62, 5, 42, 52, 48, 5]
numbers_array = arr.array('i', numbers_list)

print(numbers_array[2:5]) # 3rd to 5th


print(numbers_array[:5]) # beginning to 4th
Output:
print(numbers_array[5:]) # 6th to end array('i', [62, 5, 42])
print(numbers_array[:]) array('i', [2, 5, 62, 5, 42])
array('i', [52, 48, 5])
array('i', [2, 5, 62, 5, 42, 52, 48, 5])
Problem Solving and Python Programming
List as Arrays
Insertion: We can add one item to a list using append() function, or or
add several items using extend() function.
Example:
import array as arr
numbers = arr.array('i', [1, 2, 3])
numbers.append(4)
print(numbers) # Output: array('i', [1, 2, 3, 4])
# extend() appends iterable to the end of the array
numbers.extend([5, 6, 7])
print(numbers) # Output: array('i', [1, 2, 3, 4, 5, 6, 7])

Problem Solving and Python Programming


List as Arrays
Concatenation: We can concatenate two arrays using ‘+’ operator.
Example:
import array as arr
odd = arr.array('i', [1, 3, 5])
even = arr.array('i', [2, 4, 6])
numbers = arr.array('i') # creating empty array of integer
numbers = odd + even
print(numbers)

Problem Solving and Python Programming


List as Arrays
Deletion: We can delete one or more items from an array using ‘del’
statement.
Example:
import array as arr
number = arr.array('i', [1, 2, 3, 3, 4])
del number[2] # removing third element
print(number) # Output: array('i', [1, 2, 3, 4])
del number # deleting entire array
print(number) # Error: array is not defined

Problem Solving and Python Programming


List as Arrays
Deletion: We can also use remove() method to remove the given item or
pop() method to remove an item at the given index.

Example:
import array as arr
numbers = arr.array('i', [10, 11, 12, 12, 13])
numbers.remove(12)
print(numbers) # Output: array('i', [10, 11, 12, 13])
print(numbers.pop(2)) # Output: 12
print(numbers) # Output: array('i', [10, 11, 13])

Problem Solving and Python Programming


Illustrative Problems

Problem Solving and Python Programming


Find the square root of a number
(Newton’s method)

Problem Solving and Python Programming


Find the square root of a number
(Newton’s method)
def newtonSqrt(n, howmany):
approx = 0.5 * n

n=int(input("Enter the number for which Sq.Rt is to be found"))


howmany=int(input("Enterhowmany approximations"))
print(newtonSqrt(n, howmany))
Problem Solving and Python Programming
Find the square root of a number
(Newton’s method)
def newtonSqrt(n, howmany):
approx = 0.5 * n
while(approx>0):

betterapprox = 0.5 * (approx + n/approx)

n=int(input("Enter the number for which Sq.Rt is to be found"))


howmany=int(input("Enterhowmany approximations"))
print(newtonSqrt(n, howmany))
Problem Solving and Python Programming
Find the square root of a number
(Newton’s method)
def newtonSqrt(n, howmany):
approx = 0.5 * n
while(approx>0):
for i in range(howmany):
betterapprox = 0.5 * (approx + n/approx)
approx = betterapprox
print("Approximate square root at ",i,"th iteration is ",approx)
return betterapprox
n=int(input("Enter the number for which Sq.Rt is to be found"))
howmany=int(input("Enterhowmany approximations"))
print(newtonSqrt(n, howmany))

Problem Solving and Python Programming


Find the square root of a number
(Newton’s method)
OUTPUT:
Enter the number for which Sq.Rt is to be found36
Enterhowmany approximations7
Approximate square root at 0 th iteration is 10.0
Approximate square root at 1 th iteration is 6.8
Approximate square root at 2 th iteration is 6.047058823529412
Approximate square root at 3 th iteration is 6.00018310826276
Approximate square root at 4 th iteration is 6.000000002793968
Approximate square root at 5 th iteration is 6.0
Approximate square root at 6 th iteration is 6.0
6.0
Problem Solving and Python Programming
GCD of two numbers
print("Enter the first no.")
a=int(input())
print("Enter the second no.")
b=int(input())
rem=a%b
while(rem!=0):
a=b
b=rem Output:
Enter the first no.
rem=a%b 16
Enter the second no.
print("GCD of the given number is:",b) 12
GCD of the given number is: 4

Problem Solving and Python Programming


Exponentiation (power of a number)
def expo(base,degree):
result=1
i=1
if degree==0:
return 1  Output:
while(i<=degree): Enter the base value 5
Enter the exponent value 6
result=base*result X pow Y is 15625
i+=1
return result

base=int(input("Enter the base value"))


degree=int(input("Enter the exponent value"))
print("X pow Y is",expo(base,degree))
Problem Solving and Python Programming
Exponentiation (power of a number)
Exponentiation Program without using Function:
base=int(input("Enter Base Value:"))
exp=int(input("Enter Exponent Value"))
result=base**exp
print("Result:",result)

Output:
Enter Base Value:5
Enter Exponent Value6
Result: 15625

Problem Solving and Python Programming


Illustrative Problems: Sum an Array of Numbers
import array as arr
n=int(input("Enter Number of Elements in an Array:"))
elements=arr.array('i')
for i in range(0,n):
number=int(input("Enter the Number as:"))
elements.append(number)

print("Your Array as:",elements)

sum=0
for i in range (0,len(elements)):
sum=sum+elements[i]
print("Sum of Elements in an Array:",sum)

Problem Solving and Python Programming


Illustrative Problems: Sum an Array of Numbers

OUTPUT:
Enter Number of Elements in an Array:5
Enter the Number as:1
Enter the Number as:2
Enter the Number as:3
Enter the Number as:4
Enter the Number as:5
Your Array as: array('i', [1, 2, 3, 4, 5])
Sum of Elements in an Array: 15
Avarage of Elements in an Array: 3.0

Problem Solving and Python Programming


Illustrative Problems: Linear Search
list=[] #list declaration
size=int(input("Enter the Size of the List:"))
print("Please Enter",size,"Numbers in Sorted Order:")
for i in range(0,size): #getting the input from user and appending into the list
number=int(input("Enter Number:"))
list.append(number) #appending elements one by one into the list
print("Your List:",list)

search=int(input("Enter the item to be Search:"))


found=0 #temporary variable
for i in range(0,len(list)): #searching an item in the list
if(list[i]==search):
print("Your item is found in the position:",i)
found=1
break #quitting nearest enclosing loop once the item is found
if(found==0):
print("Sorry...Your item is not Found!!!")
Problem Solving and Python Programming
Illustrative Problems: Linear Search

OUTPUT:
Enter the Size of the List:8
Please Enter 8 Numbers
Enter Number:19
Enter Number:2
Enter Number:8
Enter Number:25
Enter Number:16
Enter Number:33
Enter Number:1
Enter Number:5
Your List: [19, 2, 8, 25, 16, 33, 1, 5]
Enter the item to be Search:16
Your item is found in the position: 4
Problem Solving and Python Programming
Illustrative Problems: Binary Search
def binarysearch(list,search):
list=[] first=0
size=int(input("Enter the Size of the List:")) last=len(list)-1

print("Please Enter",size,"Numbers in Sorted Order") found=0


for i in range(0,size):
number=int(input("Enter Number:")) while(first<=last):
midpoint=(first+last)//2
list.append(number)
if(search==list[midpoint]):
print("Your List:",list) found=1
break
search=int(input("Enter the item to be Search:")) else:
if(search<list[midpoint]):
result,index=binarysearch(list,search)
landst=midpoint-1
else:
if(result==1): first=midpoint+1
print("Your item is Found in the position:",index)
return found, midpoint
else:
print("Not Found")
Problem Solving and Python Programming
Illustrative Problems: Binary Search
OUTPUT:
Enter the Size of the List:8
Please Enter 8 Numbers in Sorted Order
Enter Number:1
Enter Number:2
Enter Number:3
Enter Number:4
Enter Number:5
Enter Number:6
Enter Number:7
Enter Number:8
Your List: [1, 2, 3, 4, 5, 6, 7, 8]
Enter the item to be Search:6
Your item is Found in the position: 5

Problem Solving and Python Programming

You might also like