Unit III – Control Flow, Func ons & Strings
Unit – III CONTROL FLOW, FUNCTIONS & STRINGS
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.
****************************************************************
Boolean Values & Operators:
• It represents a ‘true’ or ‘false’ statements.
• Boolean value is returned as a result of a comparison operators.
• Example:
print (20<5)
Output: False
Control Statements:
– determines the flow of a set of instructions.
– It decides the sequence in which the instructions in a program are to be
executed.
– Three methods of control flow are
– Sequential
– Selection
– Iterative control
Selection control/ Conditional branching
– It helps to jump from one part of code to another depending on whether a
particular condition is satisfied or not.
– i.e., they allow to execute statements selectively based on certain decisions.
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
– Types:
if statement
if – else statement
Nested if statement
If – elif – else statement
if Statement:
• It’s a selection statement based on Boolean expression.
• Test expression is evaluated if the condition is True.
Syntax:
if (test_expression):
statement Block 1
………
statement Block n
Statement X
Example: Check if a number is prime
Program:
n = int(input("enter a number :"))
if n>0:
print(n,"is positive")
Output:
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
if – else statement
• In an if – else statement,
– If the condition is true, then true block is executed.
– If the condition is false, then false block is executed.
– Statement X is executed every time.
Syntax:
if (test_expression):
statement block 1
else:
statement block 2
Statement X
Example: To find if a number is odd or even
Program:
num=int(input("enter a number:"))
if num%2==0:
print(num,"is even")
else:
print(num,"is odd")
OUTPUT
Try it out:
1. Odd or even number
2. Positive or Negative number
3. Leap year or not
4. Greatest of two numbers
5. Eligibility to vote
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
Nested if statements
• A statement that contains other statements is called a compound statement.
• Nested if statements mean an if statement inside another if statement.
• So the inner if statement is the part of the outer one.
• Nested if are used to check if more than one condition is satisfied.
Syntax:
if (test_expression 1):
if (test_expression 2):
statement block 2
else:
statement block 3
else:
statement block 1
statement block n
Example:
OUTPUT:
Try it yourself:
1. Positive, Negative or zero
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
if – elif – else statement
• Used to test additional conditions
• Elif – shortcut for else if
• With a series of if and elif statements, there’s only one final else block
• Else block executed if none of the if or elif expression is true.
Syntax:
if (test_expression 1):
statement block 1
elif (test_expression 2):
statement block 2
…………………….
elif (test_expression N):
statement block N
else:
statement block X
Statement block Y
Example:
OUTPUT:
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
ITERATIVE STATEMENTS
• Used to repeat the execution of a list of statements.
• Types:
– while loop
– for loop
for loop
• Repeat a task until a particular condition is True.
• A for loop is used for iterating over a sequence.
• Used when the number of iterations is known.
Syntax: Specify the range
for loop_control_var in sequence: of sequence
statement block
Is loop
control Statement
variable Block 1
in
Statement Block 2
• range () – used to iterate over a sequence of numbers.
• Syntax:
for i in range(beginning, end, [step])
• [step] – optional, positive or negative but not zero.
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
Example:
for loop using start and end value
for loop using only the end value
for loop using start, end, step value:
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
while loop
• Repeats one or more statements while a particular statement is True.
• The test condition is checked first. If it is true, the statement block is
executed.
• The test condition is checked repeatedly till the condition becomes False.
Syntax:
Statement X
statement x
while (condition):
statement block
statement y Update the condi on
expression
Condi
on
FALSE
Statement Block
Statement Y
TRUE
Example:
1. Sum of n numbers
OUTPUT:
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
2. Sum of Digits of a number
OUTPUT:
3. Reverse a given number
OUTPUT:
4. Armstrong number
OUTPUT
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
break loop
• Break statement - With the break statement we can stop the loop even if the
while condition is true.
• It terminates the loop with the break statement and executes the remaining
statements outside the loop.
• Syntax:
while(test expression):
if(condition for break)
break
Statements
Example:
Output
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
continue Statement:
• continue Statement – With the continue statement we can stop the current
iteration, and continue with the next.
Syntax:
while (test condition):
if(condition for continue):
continue
Statement
Example:
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
pass Statement:
• The Python pass statement is used when a statement is required
syntactically but you do not want any command or code to execute.
• The Python pass statement is a null operation; nothing happens when it
executes.
n=int(input("Enter the number:"))
if(n%2==0):
print(n,"is even")
pass
else:
print(n)
Difference between break & continue statements
How to select a loop
• Entry – controlled (pre-test):
– Condition tested before loop starts.
– If condition is not met, loop never executes.
– Choose for or while loop
• Exit – controlled (post-test):
– Conditions are tested after the loop is executed.
– Body of the loop executed unconditionally for first time.
– Choose do – while loop
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
Functions:
• A Python function is a block of
– organized,
– reusable code that is used to perform a single, related action.
• Functions provide
– better modularity for your application
– a high degree of code reusing.
• All variables created in function definitions are local variables;
• They are known only to the function in which they are declared.
Defining a Function
• Uses built – in functions and user – defined functions.
• When a function is defined, space is allocated in the memory.
• Function definition as two parts
– Function header
– Function body
Syntax
def function_name(variable1, variable2,…):
documentation string
statement block
return [expression]
• User defined functions:
– Uses def keyword
– Properly indented to form block code.
– May have a return[expression] statement.
– Can assign a function name to a variable.
– Function should be defined before calling them.
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
Function Call
def my_function():
print(“Hello from a function”)
my_function()
Output:
Hello from a function
Refer book for Function definition & function call – Important
Topic
Arguments or Parameters
• Parameters/Arguments
– It’s a variable
– Listed inside the parenthesis in the function definition.
– Any number of arguments can be added with a comma to separate
them.
Need for functions
• Simplifies program development.
• Understanding, coding and testing are easier.
• Python libraries speeds up the development.
• Code reuse
• Can be called multiple times in same program of different program.
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
Function Composition
• Combining functions, so that the result of each function is passed as the
argument of the next function.
Output:
Local & Global Variables
• Two types of variables
– Local variable: limited to the function where it is defined
– Global variable: available for the entire program
Example:
Local Variable:
Output:
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
Global Variable:
Output:
Function Recursion
• A function that calls itself directly or indirectly.
• Two cases
– Base case:
• Problem is simple enough to be solved directly without any
calls to the same function.
– Recursive case:
• First, Problem is divided into simpler sub-parts.
• Second, function calls itself but with sub-parts of the problem
from the first step.
• Result is combination of solutions to simpler sub-parts.
Example: Factorial of a number
Output:
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
List as an array
Why array?
• Collection of similar data types
• Stored in continuous memory locations.
• Idea:
• To store multiple items of same datatypes together.
Why an array instead of list
Arrays
• For scientific computing arrays are used over lists.
• Array of numeric values is supported through array module.
• Arrays stores elements of a single datatype.
• Stores fixed number of elements.
Key terms used:
• Element – each item stored in an array
• Index – location of each element in the array
Creating an array
• Created by importing an array module.
import array as array1
• Syntax:
• Arrayname = array(data_type, values)
• Example:
a = [Link](‘i’, [1,2,3,4,5,6,7,8])
Basic operations
• Traverse – prints all array elements one by one
• Insertion – adds an element in the array at the specified index
• Deletion – deletes an element from array from a specified index.
• Search – searches to check if a value is present or not.
• Update – updates/changes the value of an specified element
Example:
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
Output:
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
Illustrative Problems:
1. Square root of a number
Output:
2. GCD
Output:
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
3. Exponentiation
Exponentiation is the process of raising a number to a certain power.
A recursive function to computer exponentiation can be defined as
o Base condition:
If exponent = 1, return base value
o Recursive condition:
Else, return the base number multiplied with the power
function called recursively with the arguments as the base
and exp-1
Output:
Program Explanation:
Get the base and exponential value from the user.
The numbers are passed as arguments to a recursive function to find the
power of the number.
The base condition is given that if the exponential = 1, the base value is
returned.
If the exponential power isn’t equal to 1, the base number is multiplied
with the power function is called recursively with the arguments as the
base and exp-1.
The result is printed.
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
4. Sum an array of numbers
Output:
5. Linear search
Linear search, also known as sequential search, is used to find an
element within a list or array.
Idea: sequentially check each element in the list/array until a match is
found or the end of the list is reached.
Steps:
1. Start at the beginning of the list/array.
2. Compare the search element with the current element in the list.
3. If there is a match, the search is successful and the index of the
element is returned.
4. If there is no match, move on to the next element in the list.
5. Else, if the search element is not in the list, then -1, indicating that
the element is not present is returned.
Advantages:
o Easy to implement.
Disadvantages:
o Not efficient for large datasets.
o Time complexity is O(n)
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
Output:
6. Binary search.
Binary search is a search algorithm that finds the position of a search
element within a sorted array. It works by recursively dividing the
search array/list in half.
Steps:
o Set two pointers, the l – the left index (start of the array) and r –
the right index (end of the array)
o Calculate the mid - middle element of the array/list and compare
it with the search element (a)
o If the middle element is equal to the search element, the search is
successful & index is returned.
o If the search element is lesser than the middle element, the search
continues in the left half of the array, thereby discarding the right
half.
o If the search element is greater than the middle element, the
search continues in the right half of the array, thereby discarding
the left half.
o Repeat the steps until the search element is found.
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
Advantages:
o Time complexity is O(log n), making it very efficient.
Program:
Output:
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
STRINGS
• Group of characters.
• They are immutable.
• Using single quotes (‘)
• Using double quotes (“)
• Using triple quotes(’’’) – multi line strings
• Syntax: ‘hello’ , “hello”
Accessing characters in a String
• Strings can be accessed using indexing.
• There are two types of indexing: positive indexing & negative indexing
0 1 2 3 4 5 6 7 8 9
A B C D E F G H I J
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
• Example:
str = “ABCDEFGHIJ”
print(str[4]) = E
print(str[-6]) = E
String Operations:
1. String Slicing
• Used to access a range of characters in the String.
• Slicing operator colon( : )
• Example:
string = “Hello, World”
• To slice from start:
b = "Hello, World!"
GE3151 - PSPP P. Preethika, AP/IT, LICET 1
Unit III – Control Flow, Func ons & Strings
print(b[:8])
O/P: Hello, W
2. String Concatenation:
3. String repetition
4. String Reverse
OUTPUT:
GE3151 - PSPP P. Preethika, AP/IT, LICET 1