Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

GE8151 Unit III

Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

1

UNIT III 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.

3.1 CONDITIONALS:
3.1.1 BOOLEAN VALUES AND OPERATORS
A Boolean expression is an expression that is either true or false. It is used to compare two
values.
The following examples 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'>
Remember that = is an assignment operator and == is the relational operator.

Program:
x=12
y=15
print(―is x == y ? =‖ ,x == y )
print(―is x != y ? =‖ ,x != y )
print(―is x <= y ? =‖ ,x <= y )
print(―is x >= y ? =‖ ,x >= y )
print(―is x > y ? =‖ ,x > y )
print(―is x < y ? =‖ ,x < y )
Output:
is x == y ? = False
is x != y ? =True
is x <= y ? =True
is x >= y ? =False
is x > y ? =False
is x < y ? =True

Mr. P. J. Merbin Jose


2

LOGICAL OPERATORS (BOOLEAN OPERATORS)


There are three Logical operators: and, or, and not .The semantics of these operators is similar
to their meaning in English. These logical operators are referred as Boolean operators.
For example, x > 0 and x < 10 is true only if x is greater than 0 and less than 10. Another
example, n%2 == 0 or n%3 == 0 is true if either or both of the conditions is true, that is, if the
number is divisible by 2 or 3.
Finally, the not operator negates a boolean expression, so not (x>y) is true if x>y is false, that
is, if x is less than or equal to y.

Operator Meaning Example


And True if both the operands are true x and y x y x and y
T T T
T F F
F T F
F F F
Or True if either of the operands is true x or y x y x or y
T T T
T F T
F T T
F F F
Not True if operand is false not x x not x
(complements the operand) T F
F T

Eg:

x = True
y = False
print('x and y is', x and y)
print('x or y is', x or y)
print('not x is', not x)
Output:
x and y is False
x or y is True
not x is False

CONDITIONAL BRANCHING STATEMENTS:


In order to write useful programs, we almost always need the ability to check conditions and
change the behavior of the program accordingly. Conditional Branching statements give this
ability. Python language supports different types of conditional branching statements. They are:
 Conditional Execution(if)
Mr. P. J. Merbin Jose
3

 Alternative Execution (if-else)


 Chained Conditinals(if-elif-else)
 Nested Conditionals

3.1.2 CONDITIONAL (if)


The if statement is the simplest form of decision control statement that is frequently used
in decision making.
Syntax:
if test_ expression:
Statements

 The Colon(:) is required at the end of the condition

The boolean expression after if is called the condition. If it is true, the indented statement runs.
If not, nothing happens.
if statements have the same structure as function definitions: a header followed by an indented
body. Statements like this are called compound statements.

Flowchart:

Fig: Flowchart if statement


Program:
x=8
if x > 0:
print(x,"x is positive")

There is no limit on the number of statements that can appear in the body, but there has to be at
least one. Occasionally, it is useful to have a body with no statements. In that case, you can use
the pass statement, which does nothing.
Ex:
x=7
if x < 0:
pass # TODO: need to handle negative values!

Example:

Mr. P. J. Merbin Jose


4

Program to provide flat Rs 500, if the purchase amount output


is greater than 2000.
purchase=eval(input(―enter your purchase amount‖)) enter your purchase
if(purchase>=2000): amount
purchase=purchase-500 2500
print(―amount to pay‖,purchase) amount to pay
2000
Program to provide bonus mark if the category is sports output

m=eval(input(―enter ur mark out of 100‖)) enter ur mark out of 100


c=input(―enter ur categery G/S‖) 85
if(c==‖S‖): enter ur categery G/S
m=m+5 S
print(―mark is‖,m) mark is 90

3.1.3 ALTERNATIVE (if-else)


A second form of the if statement is Alternative Execution, in which there are two
possibilities and the condition determines which one gets executed.
The syntax looks like this:
if(condition):
True Statement(s)
else:
False Statement(s)

Fig: Flowchart if-else statement


Eg:# Program checks if the number is odd or even
x=10
if(x%2==0):
print("x is even")
else:
print("x is odd")

Mr. P. J. Merbin Jose


5

If the remainder when x is divided by 2 is 0, then we know that x is even, and the program
displays a message to that effect. If the condition is false, the second set of statements is
executed. Since the condition must be true or false, exactly one of the alternatives will run. The
alternatives are called branches, because they are branches in the flow of execution.

Example:
Odd or even number Output
n=eval(input("enter a number")) enter a number4
if(n%2==0): even number
print("even number")
else:
print("odd number")
positive or negative number Output
n=eval(input("enter a number")) enter a number8
if(n>=0): positive number
print("positive number")
else:
print("negative number")
leap year or not Output

y=eval(input("enter a yaer")) enter a yaer2000


if(y%4==0): leap year
print("leap year")
else:
print("not leap year")
greatest of two numbers Output
a=eval(input("enter a value:")) enter a value:4
b=eval(input("enter b value:")) enter b value:7
if(a>b): greatest: 7
print("greatest:",a)
else:
print("greatest:",b)

eligibility for voting Output


age=eval(input("enter ur age:")) enter ur age:78
if(age>=18): you are eligible for vote
print("you are eligible for vote")
else:
print("you are eligible for vote")

3.1.4 CHAINED CONDITIONALS (if-elif-else statement)

Mr. P. J. Merbin Jose


6

Sometimes there are more than two possibilities and we need more than two branches. One way
to express this type of computation is a chained conditional:
The syntax looks like this:
if (condition1):
statement(s)
elif(condition2):
statement(s)
elif(condition3):
statement(s)
else:
statement(s)

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.
Eg:
# Check positive or negative
num = int(input("enter a num"))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

Fig: Flowchart if –elif-else statement


Eg:
7

if choice == 'a':
draw_a()
elif choice == 'b':
draw_b()
elif choice == 'c':
draw_c()

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.

Example:
student mark system Output
mark= eval(input("enter ur mark:")) enter ur mark:78
if(mark>=90): grade:B
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")
traffic light system Output
colour=input("enter colour of light:") enter colour of light:green
if(colour=="green"): GO
print("GO")
elif(colour=="yellow"):
print("GET READY")
else:
print("STOP")
compare two numbers Output
x=eval(input("enter x value:")) enter x value:5
y=eval(input("enter y value:")) enter y value:7
if(x == y): x is less than y
print("x and y are equal")
elif(x < y):
print("x is less than y")
else:
print("x is greater than y")
Roots of quadratic equation output
8

a=eval(input("enter a value:")) enter a value:1


b=eval(input("enter b value:")) enter b value:0
c=eval(input("enter c value:")) enter c value:0
d=(b*b-4*a*c) same and real roots
if(d==0):
print("same and real roots")
elif(d>0):
print("diffrent real roots")
else:
print("imaginagry roots")

NESTED CONDITIONALS
One conditional can also be nested within another.
#Check positive or negative
num = float(input("enter a num"))
if num>= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
The outer conditional contains two branches. The first branch contains a simple
statement. The second branch contains another if statement, which has two branches of its own.
Those two branches are both simple statements, although they could have been conditional
statements as well.

Although the indentation of the statements makes the structure apparent, nested
conditionals become difficult to read very quickly.

Logical operators often provide a way to simplify nested conditional statements. For
example, we can rewrite the following code using a single conditional:
x=5
if 0 < x:

if x < 10:

print ('x is a positive single-digit number.')

Output:
x is a positive single-digit number.

The print statement is executed only if we make it past both conditionals, so we can get
the same effect with the ‗and‘ operator:
9

x=5
if 0 < x and x < 10:
print('x is a positive single-digit number.')

Output:
x is a positive single-digit number.

Python also provides a more concise option:


x=5
if 0 < x < 10:
print 'x is a positive single-digit number.'

Output:
x is a positive single-digit number.

Reassignment
It is legal to make more than one assignment to the same variable. A new assignment makes an
existing variable refer to a new value (and stop referring to the old value).
>>> x = 5
>>> x
5
>>> x = 7
>>> x
7
The first time we display x, its value is 5; the second time, its value is 7.
Figure, shows what reassignment looks like in a state diagram.

(1) 5
x

(2) 7

Fig: State Diagram

State: Transition from one process to another process under specified condition with in a
time is called state

In python an assignment statement can make two variables equal. But they don‘t have to stay
that way:
>>>a=5
>>>a=b #a and b are now equal
>>>a=3 #a and b are no longer equal
10

>>>b
5
The third line changes the value of a but does not change the value of b, so they are no longer
equal.

Reassigning variables is often useful, but it has to be used with caution. If the values of the
variables change frequently, it can make the code difficult to read and debug.

Updating Variables
A common kind of reassignment is an update, where the new value of the variable depends on
the old.
>>> x = x + 1
This means ―get the current value of x, add one, and then update x with the new value.‖
If we try to update a variable that doesn‘t exist, we get an error, because Python evaluates the
right side before it assigns a value to x:
>>> x = x + 1
NameError: name 'x' is not defined
Before we can update a variable, we have to initialize it, usually with a simple assignment:
>>> x = 0
>>> x = x + 1
Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement.

3.2 ITERATION:
Iteration is an ability to run a block of statements repeatedly. Python allows a block of
statements to be repeated as many times as long as the processor could support. This is generally
called looping, also called as repetition structure or iteration.

In python iteration can be achieved by three ways:


 While Statement
 For statement
 Nested Loops

A looping statement also influences the flow of control because it causes one or more statements
or a block to be executed repeatedly.

Any looping statement would include the following steps:


i) Initialization of condition variable
ii) Test the control statement
iii) Executing the body of the loop depending on the condition
iv) Updating the condition variable.
11

3.2.1 The while statement

The keyword while followed by a test expression (which can be any valid expression),
and a colon. Following the header is an indented body. The test expression is evaluated. If it
evaluates to True, then the body of the loop is executed. After executing the body, the test
expression is evaluated again. While test expression evaluates to True, the body of the loop is
executed. When the test expression evaluates to False, the loop is terminated and execution
continues with the statement following the body.

Syntax:
while (condition):
body of the loop

Fig: Flowchart of while loop

Example program:
i=0
n=5
while i<=n:
print (i)
i+=1

Output:
0
1
2
3
4
5
12

Example:

Sum of n numbers: Output


n=eval(input("enter n")) enter n
i=1 10
sum=0 55
while(i<=n):
sum=sum+i
i=i+1
print(sum)
Factorial of a numbers: output
n=eval(input("enter n")) enter n
i=1 5
fact=1 120
while(i<=n):
fact=fact*i
i=i+1
print(fact)
Sum of digits of a number: output
n=eval(input("enter a number")) enter a number
sum=0 123
while(n>0): 6
sum=sum+a
n=n//10
print(sum)
Armstrong number or not Output
n=eval(input("enter a number")) enter a number153
org=n Armstrong number
sum=0
while(n>0):
a=n%10
sum=sum+a*a*a
n=n//10
if(sum==org):
print(―Armstrong number‖)
else:
print(―Not an Armstrong number‖)
Palindrome or not Output
n=eval(input("enter a number")) enter a number121
org=n The given no is palindrome
sum=0
13

while(n>0):
a=n%10
sum=sum*10+a
n=n//10
if(sum==org):
print("The given no is palindrome")
else:
print("The given no is palindrome")

3.2.2 The for Statement

Python‘s for statement iterates over the items of any sequence (a list or a string), in the
order that they appear in the sequence. A for statement is also called a loop because the flow of
execution runs through the body and then loops back to the top.

Syntax:
for iterating_var in sequence:
statement(s)

The range() function

If we do need to iterate over a sequence of numbers, the built-in function range() comes
in handy. It generates arithmetic progressions:
Eg:

# Prints out the numbers 0,1,2,3,4


for x in range(5):
print(x)

This function does not store all the values in memory, it would be inefficient. So it
remembers the start, stop, step size and generates the next number on the go.

for in sequence
 The for loop in Python is used to iterate over a sequence (list, tuple, string).
Iterating over a sequence is called traversal. Loop continues until we reach the
last element in the sequence.
 The body of for loop is separated from the rest of the code using indentation.

for i in sequence:
print i

Sequence can be a list, strings or tuples


14

Sl No sequences example output


1. for i in "Python": P
. For loop in string print(i) y
t
h
o
n
2. for i in [2,3,5,6,9]: 2
For loop in list print(i) 3
5
6
9

3. for i in (2,3,1): 2
For loop in tuple print(i) 3
1
o

Fig: Flowchart- for loop


Eg:
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
print("The sum is", sum)
15

Output:
The sum is 48

print nos divisible by 5 not by 10 output


n=eval(input("enter a")) enter a:30
for i in range(1,n,1): 5
if(i%5==0 and i%10!=0): 15
print(i) 25

Fibonacci series output


a=0 Enter the number of terms: 6
b=1 Fibonacci Series:
n=eval(input("Enter the number of terms: ")) 01
print("Fibonacci Series: ") 1
print(a,b) 2
for i in range(1,n,1): 3
c=a+b 5
print(c) 8
a=b
b=c
find factors of a number Output
n=eval(input("enter a number:")) enter a number:10
for i in range(1,n+1,1): 1
if(n%i==0): 2
print(i) 5
10

Nested Loops
Python programming language allows to use one loop inside another loop. Following section
shows few examples to illustrate the concept.
Syntax:

for iterating_var in sequence:


for iterating_var in sequence:
statements(s)
statements(s)

The syntax for a nested while loop statement in Python programming language is as follows
while expression:
while expression:
statement(s)
statement(s)
16

3.2.3 Python break and continue

The break statement terminates the loop containing it. Control of the program flows to
the statement immediately after the body of the loop.

If break statement is inside a nested loop (loop inside another loop), break will terminate
the innermost loop.

The working of break statement in for loop and while loopis shown below.

Eg:

# Prints out 0,1,2,3,4


count = 0
while True:
print(count)
count += 1
if count >= 5:
break

Example Output
for i in "welcome": if(i=="c"): w
break e
print(i) l

The continue statement is used to skip the rest of the code inside a loop for the current iteration
only. Loop does not terminate but continues on with the next iteration.
The working of continue statement in for and while loop is shown in figure.
17

Eg:

# Prints out only odd numbers - 1,3,5,7,9


for x in range(10):
# Check if x is even
if x % 2 == 0:
continue
print(x)

Example Output
for i in ―welcome‖: w
if (i == ―c‖): e
continue l
print(i) o
m
e

3.2.4 Python pass statement


The pass statement does nothing. It can be used when a statement is required
syntactically but the program requires no action.

Eg:
>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...
This is commonly used for creating minimal classes:
>>> class MyEmptyClass:
... pass
18

Example Output
for i in ―welcome‖: w
if (i == ―c‖): e
pass l
print(i) c
o
m
e

Control Statement & Description


S.No Control Statement Description
1. break statement Terminates the loop statement and transfers execution
to the statement immediately following the loop.
2. continue statement Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
3. pass statement The pass statement in Python is used when a statement
is required syntactically but you do not want any
command or code to execute.

ELSE STATEMENT IN LOOPS:


Else in for loop
 If else statement is used in for loop, the else statement is executed when the loop
has reached the limit.
 The statements inside for loop and statements inside else will also execute

Example:
for i in range(1,6):
print(i)
else:
print("the number greater than 6")
Output
1
2
3
4
5
the number greater than 6

Else in While Loop:


 If else statement is used within while loop , the else part will be executed
when the condition become false.
 The statements inside for loop and statements inside else will also execute.
19

Example:
i=1
while(i<=5):
print(i)
i=i+1
else:
print("the number greater than 5")
Output:
1
2
3
4
5
the number greater than 5

3.3 FRUITFUL FUNCTIONS


The built-in functions we have used, such as abs, pow, and max, have produced results.
Calling each of these functions generates a value, which we usually assign to a variable or use as
part of an expression.
A function that returns a value is called fruitful function.
Example:
Root=sqrt(25)
Example:
def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)

3.3.1 RETURN VALUES


return keywords are used to return the values from the function.
Example:
return a – return 1 variable
return a,b– return 2 variables
return a,b,c– return 3 variables
return a+b– return expression
return 8– return value

Consider the example function area, which returns the area of a circle with the given
radius:
20

def area(radius):
temp = 3.14159 * radius**2
return temp

In a fruitful function the return statement includes a return value. This statement means:
Return immediately from this function and use the following expression as a return value.
def area(radius):
return 3.14159 * radius**2

Code that appears after a return statement, or any other place the flow of execution can
never reach, is called dead code.

3.3.2 PARAMETERS/ARGUMENTS
 Parameters are the variables which used in the function definition.
Parameters are inputs to functions. Parameter receives the input from
the function call.
 It is possible to define more than one parameter in the function definition.
Types of parameters/Arguments:
1. Required/Positional parameters
2. Keyword parameters
3. Default parameters
4. Variable length parameters

Required/ Positional Parameter:


The number of parameter in the function definition should match exactly with
number of arguments in the function call.

Example Output:
def student( name, roll ): George 98
print(name,roll)
student(―George‖,98)

Keyword parameter:
When we call a function with some values, these values get assigned to the
parameter according to their position. When we call functions in keyword parameter, the
order of the arguments can be changed.
Example Output:
def student(name,roll,mark): 90 102 bala
print(name,roll,mark)
student(90,102,"bala")
21

Default parameter:
Python allows function parameter to have default values; if the function is called without
the argument, the argument gets its default value in function definition.

Example Output:
def student( name, age=17): Kumar 17
print (name, age)
Ajay 17
student( ―kumar‖)
student( ―ajay‖)

Variable length parameter



Sometimes, we do not know in advance the number of arguments that will be passed into
a function.


Python allows us to handle this kind of situation through function calls with number of
arguments.


In the function definition we use an asterisk (*) before the parameter name to denote this
is variable length of parameter.

Example Output:
def student( name,*mark): bala ( 102 ,90)
print(name,mark)
student (―bala‖,102,90)

3.3.3 LOCAL AND GLOBAL SCOPE


Global Scope
The scope of a variable refers to the places that you can see or access a variable.
(Scope of a variable is the portion of a program where the variable is recognized).
 A variable with global scope can be used anywhere in the program.
 It can be created by defining a variable outside the function.
22

Local Scope
A variable with local scope can be used only within the function. Parameters and
variables defined inside a function is not visible from outside. Hence, they have a local scope.

Example:
a=50 --------------------------------------------------Global variable
def add():
b=20--------------------------------------------Local variable
c=a+b
print c
def sub():
b=30--------------------------------------------Local variable
c=a-b;
print c
print a
add()
sub()

Output:
50
70
20

3.3.4 FUNCTION COMPOSITION

 The ability to call one function from within another function


 It is a way of combining functions such that the result of each function is passed as the
argument of the next function.
 In other words the output of one function is given as the input of another function is
known as function composition.

Example:
math.sqrt(math.log(10))
23

Example: Output:
def add(a,b): 900
c=a+b
return c
def mul(c,d):
e=c*d
return e
c=add(10,20)
e=mul(c,30)
print(e)
find sum and average using function output
Composition
def sum(a,b): enter a:4
sum=a+b enter b:8
return sum the avg is 6.0
def avg(sum):
avg=sum/2
return avg
a=eval(input("enter a:"))
b=eval(input("enter b:"))
s=sum(a,b)
a=avg(s)
print("the avg is",a)

Example: To find area of a circle

def distance(x1, y1, x2, y2): #distance between 2 points


L1=(x2-x1)**2+(y2-y1)**2
Distance=L1**0.5
return Distance

def area(radius):
return 3.14159 * radius**2

def
 area2(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp)) #function Composition

xc=eval(input(‗Enter Center point x1: ‗)


yc= eval(input(‗Enter Center point y1: ‗)
xp=eval(input(‗Enter point x2 in perimeter: ‗)
yp= eval(input(‗Enter point y2 in perimeter: ‗)
A=area2(xc, yc, xp, yp) #function call
print A
24

3.3.5 RECURSION:
 Recursion is the process of defining something in terms of itself.
 A function can call other functions. It is even possible for the function to call itself. These
types of construct are termed as recursive functions.
 A function calling itself till it reaches the base value - stop point of function call.
Example: factorial of a given number using recursion

Factorial of n Output
def fact(n): enter no. to find fact:5
if(n==1): Fact is 120
return 1
else:
return n*fact(n-1)
n=input(―enter no.to find fact:‖)
fact=fact(n)
print("Fact is",fact)

Note: Refer Unit I- Recursion


(example, advantage, disadvantage etc)

The Anonymous Functions - LAMDA


These functions are called anonymous because they are not declared in the standard
manner by using the def keyword. You can use the lambda keyword to create small anonymous
functions.
 Lambda forms can take any number of arguments but return just one value in the
form of an expression. They cannot contain commands or multiple expressions.
 An anonymous function cannot be a direct call to print because lambda requires
an expression
 Lambda functions have their own local namespace and cannot access variables
other than those in their parameter list and those in the global namespace.
 Although it appears that lambda's are a one-line version of a function, they are not
equivalent to inline statements in C or C++, whose purpose is by passing function
stack allocation during invocation for performance reasons.
Syntax
The syntax of lambda functions contains only a single statement, which is as follows
lambda [arg1 [,arg2,.....argn]]:expression

Example: Program to demonstrate the use of lamda function


# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;
# Now you can call sum as a function
25

print "Value of total : ", sum( 10, 20 )


print "Value of total : ", sum( 20, 20 )
Output:
Value of total : 30
Value of total : 40

Use of Lambda function


We use lambda functions when we require a nameless function for a short period of time.
Lambda function are used along with built-in functions like filter(),map() etc.

Filtering
The filter() function in Python takes in a function and a list as arguments. The function is
called with all the items in the list and a new list is returned which contains items for which the
function evaluates to true.
The function filter(function, list) offers an way to filter out all the elements of a list, for
which function returns True.

Example: Program to demonstrate the use of filter in lamda function


# Function definition is here
my-list =[1,2,3,4,5,6,7,8,9,10]
new-list=list(filter(lambda n: (n%2 == 0),my-list))
print(new-list)

3.4 STRINGS
 String is defined as sequence of characters represented in quotation marks(either single quotes
( ‗ ) or double quotes ( ― ) or (―‖‖ ―‖‖‖)
 An individual character in a string is accessed using an index.
 The index should always be an integer (positive or negative).
 A index starts from 0 to n-1.

 Strings are immutable i.e. the contents of the string cannot be changed after it is
created.
 Python will get the input at run time by default as a string.

 Python does not support character data type. A string of size 1 can be treated as
characters.

String A H E L L O
Positive Index 0 1 2 3 4
Negative Index -5 -4 -3 -2 -1
26

Summary of operations:

Indexing >>>a=‖HELLO‖ Positive indexing helps in


>>>print(a[0]) accessing
>>>H the string from the
>>>print(a[-1])
beginning
>>>O
Negative indexing helps in
accessing the string from
the end
Print[0:4] – HELL The
Slicing: Print[ :3] – HEL slice[start:stop]operator
extracts substrings from
Print[0: ]-
the string
HELLO A segment of a string is
called a slice
a=‖save‖ The + operator joins the
Concatenation b=‖earth‖ text on both
>>>print(a+b) sides of the operator.
saveearth
a=‖panimalar ‖ The * operator repeats the
Repetitions: >>>print(3*a) string on the
panimalarpanimalar left hand side times
panimalar the value on right
hand side.

Membership: >>> s="good morning" Using membership


>>>"m" in operators to check a
s True particular character is
>>> "a" not in s in string or not.
True Returns true if present

Searching
Example: Program to find the letter in a word
def find(word, letter):
index = 0
while index < len(word):
if word[index] == letter:
return index
index = index + 1
return -1

If the character is not found, the function returns -1. If word[index] == letter, the function breaks
out of the loop and returns immediately. If the character doesn‘t appear in the string, the program
exits the loop normally and re-turns -1. This pattern of computation—traversing a sequence and
returning when we find what we are looking for—is called a search.
27

Looping and counting


The following program counts the number of times the letter a appears in a string:
Example: Program to counts the number of times the letter a appears in a string
word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print(count)

3.4.1 STRING SLICES


A segment of a string is called a slice. Selecting a slice is similar to selecting a character. The
process of extracting a sub string from a string is called slicing. We can access a range of items
in a string by using the slicing operator (colon).
Syntax:

substring = original_string[first_pos:last_pos]

Example:
>>> s = 'Monty Python'
>>> s[0:5]
'Monty'
>>> s[6:12]
'Python'

If the first index is greater than or equals to the second the result is an empty string, represented
by two quotation marks:
>>> fruit = 'banana'
>>> fruit[3:3]
''

Print[0:4] – HELL The Slice[n : m] operator extracts


Slicing: Print[ :3] – HEL sub string from the strings.
a=”HELLO” Print[0: ]- HELLO A segment of a string is called a slice.

3.4.2 IMMUTABILITY

In Python, Strings are immutable. This means that elements of a string cannot be changed once it
has been assigned. Therefore [ ] operator cannot be used on the left side of an assignment.

>>>mystring = 'programiz‗
>>>mystring[5] = ‗b'
TypeError: 'str' object does not support item assignment.

We cannot delete or remove characters from a string. But deleting the string entirely is possible
using the keyword del.
28

>>>del mystring.

OPERATIONS EXAMPLE OUTPUT


ELEMENT a="PYTHON" TypeError: 'str' object does
ASSIGNMENT a[0]=‘x‘ not support element
assignment
a=‖PYTHON‖ TypeError: 'str' object
ELEMENT del a[0] doesn't support element
DELETION deletion

DELETE A STRING a=‖PYTHON‖ NameError: name


del a 'my_string' is not defined
print(a)

3.4.3 STRING BUILTIN FUNCTIONS AND METHODS:


A method is a function that ―belongs to‖ an object.

Syntax to access the method

Stringname.method()

a=‖happy birthday‖
here, a is the string name.

Syntax example description

1 a.capitalize() >>> a.capitalize() capitalize only the first letter


' Happy birthday in a string

2 a.upper() >>> a.upper() change string to upper case

'HAPPY BIRTHDAY‘
3 a.lower() >>> a.lower() change string to lower case

' happy birthday‘


4 a.title() >>> a.title() change string to title case i.e. first
' Happy Birthday ' characters of all the words are
capitalized.

5 a.swapcase() >>> a.swapcase() change lowercase characters


'HAPPY BIRTHDAY' to uppercase and vice versa
6 a.split() >>> a.split() returns a list of words
['happy', 'birthday'] separated by space
29

7 a.center(width, >>>a.center(19,‖*‖) pads the string with the specified


‖fillchar‖) '***happy birthday***' ―fillchar‖ till length is equal to
―width‖
8 a.count(substring) >>> a.count('happy') Returns the number of occurrences of
1 substring
9 a.replace(old,new) >>>a.replace('happy', Replace all the old substring with new
'wishyou happy') substring
'wishyou happy birthday'
10 a.join(b) >>> b="happy" returns a string concatenated with the
>>> a="-" elements of an iterable. (Here ―a‖ is
>>> a.join(b) the iterable)
'h-a-p-p-y'
11 a.isupper() >>> a.isupper() checks whether all the case- based
False characters (letters) of the string are
uppercase.
12 a.islower() >>> a.islower() checks whether all the case- based
True characters (letters) of the string are
lowercase
13 a.isalpha() >>> a.isalpha() checks whether the string consists of
False alphabetic characters only
14 a.isalnum() >>> a.isalnum() checks whether the string consists of
False alphanumeric characters.
15 a.isdigit() >>> a.isdigit() checks whether the string consists of
False digits only.
16 a.isspace() >>> a.isspace() checks whether the string consists of
False white spaces only.
17 a.istitle() >>> a.istitle() checks whether the string is title case
False
18 a.startswith(subs >>> a.startswith("h") checks whether the string starts with
tring) True substring
19 a.endswith(subst >>> a.endswith("y") checks whether the string ends with
ring) True substring
20 a.find(substring) >>> a.find("happy") returns index of substring, if it is
0 found. Otherwise -1 is returned.
21 len(a) >>>len(a) Return the length of the string
>>>14
22 min(a) >>>min(a) Return the minimum character in the
>>>‘ ‗ string
23 max(a) max(a) Return the maximum character in the
>>>‘y‘ string
30

Boolean Methods
str.isalnum() - String consists of only alphanumeric characters (no symbols)
str.isalpha() - String consists of only alphabetic characters (no symbols)
str.islower() - String‘s alphabetic characters are all lower case
str.isnumeric() - String consists of only numeric characters
str.isspace() -String consists of only whitespace characters
str.istitle() - String is in title case
str.isupper() - String‘s alphabetic characters are all upper case
Example
>>>number = "5"
>>>letters = "abcdef"
>>>print(number.isnumeric())
True
>>>print(letters.isnumeric())
False
3.4.4 String Modules:
A module is a file containing Python definitions, functions, statements. Standard
library of Python is extended as modules. To use these modules in a program, programmer
needs to import the module. Once we import a module, we can reference or use to any of its
functions or variables in our code. There is large number of standard modules also available
in python. Standard modules can be imported in the same way as we import our user-defined
modules.
Syntax:
import module_name

Example output
import string
print(string.punctuation) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.digits) 0123456789
print(string.printable) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
KLMNOPQRSTUVWXYZ!"#$%&'()*+,-, ./:;<=>?@[\]^_`{|}~
print(string.capwords("happ Happy Birthday
y birthday"))
print(string.hexdigits) 0123456789abcdefABCDEF
print(string.octdigits) 01234567
31

Escape sequences in string

Escape Description example


Sequence
\n new line >>> print("hai \nhello")
hai
hello
\\ prints Backslash (\) >>> print("hai\\hello")
hai\hello
\' prints Single quote (') >>> print("'")
'
\" prints Double quote (") >>>print("\"")
"
\t prints tab space >>>print(―hai\thello‖)
hai hello
\a ASCII Bell (BEL) >>>print(―\a‖)

3.5 LIST AS ARRAY:


Array:

Array is a collection of similar elements. Elements in the array can be accessed by


index. Index starts with 0. Array can be handled in python by module named array.
To create array have to import array module in the program.
Syntax:
import array
Syntax to create array:
Array_name = module_name.function_name(‘datatype’,[elements])

Example:
a=array.array(‘i’,[1,2,3,4])
a - array name
array - module name
i - integer datatype

Example
Program to find sum of array elements Output
import array 10
sum=0
a=array.array('i',[1,2,3,4])
for i in a:
sum=sum+i
print(sum)
32

Convert list into array:


fromlist() function is used to append list to array. Here the list is act like an array.

Syntax:
arrayname.fromlist(list_name)

Example
Program to convert list Output into array
import array
sum=0
l=[6,7,8,9,5]
a=array.array('i',[])
a.fromlist
(l)
for i in a:
sum=sum+i
print(sum)

Methods in array
Example: a=[2,3,4,5]

Syntax example Description


1 array(data type, array(‗i‘,[2,3,4,5]) This function is used to create an
value list) array with data type and value list
specified in its arguments.

2 append() >>>a.append(6) This method is used to add the at the


[2,3,4,5,6] end of the array.

3 insert(index,element) >>>a.insert(2,10) This method is used to add the value


[2,3,10,5,6] at the position specified in its
argument.

4 pop(index) >>>a.pop(1) This function removes the


[2,10,5,6] element at the position
mentioned in its argument, and returns
it.

5 index(element) >>>a.index(2) This function returns the index of


0 value
33

6 reverse() >>>a.reverse() This function reverses the array


[6,5,10,2]
a.count() This is used to count number of
7 count() 4 elements in an array

3.5 ILLUSTRATIVE PROGRAMS:


Finding Square roots
Loops are often used in programs that compute numerical results by starting with an
approximate answer and iteratively improving it. For example, one way of computing square
roots is Newton‘s method.
To find the square root of a, start with almost any estimate, x, and compute a better
estimate with the following formula:
y = (x + a/x ) 2

For example, if a is 4 and x is 3:


>>> a = 4
>>> x = 3
>>> y = (x + a/x) / 2
>>> y
2.16666666667
>>> x = y
>>> y = (x + a/x) / 2
>>> y
2.00641025641
After a few more updates, the estimate is almost exact:
>>> x = y
>>> y = (x + a/x) / 2
>>> y
2.00001024003
>>> x = y
>>> y = (x + a/x) / 2
>>> y
2.00000000003
>>> x = y
>>> y = (x + a/x) / 2
>>> y
2.0
>>> x = y
>>> y = (x + a/x) / 2
>>> y
2.0
When y == x, we can stop. Here is a loop that starts with an initial estimate, x, and improves it
until it stops changing:
34

Example 1: Program to find the square root of a number.


x=1
while True:
print(x)
y = (x + a/x) / 2
if y == x:
break
x=y
print(“The square root of”, a , “is:”, x)

Example 2:Square root


defnewtonSqrt(n):
approx = 0.5 * n
better = 0.5 * (approx + n/approx)
while better != approx:
approx = better
better = 0.5 * (approx + n/approx)
returnapprox
num= int(input("Enter the number: "))
print('The square root is' ,newtonSqrt(num))

GCD of two numbers


defcomputeGCD(x, y):
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
gcd = i
returngcd
# take input from the user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The GCD. of", num1,"and", num2,"is", computeGCD(num1, num2))

Exponentiation
def power(base,exp):
if(exp==1):
return(base)
if(exp!=1):
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value: "))
print("Result:",power(base,exp))

Sum an array of numbers


Program to add natural numbers upto sum = 1+2+3+...+n
35

# To take input from the user,


n = int(input("Enter n: "))
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
Output:
Enter n:5
The sum is 15
Linear search
def search(alist,item):
pos=0
found=False
stop=False
while pos<len(alist) and not found and not stop:
if alist[pos]==item:
found=True
print("element found in position",pos)
else:
if alist[pos]>item:
stop=True
else:
pos=pos+1

return found
a=[]
n=int(input("enter upper limit"))
for i in range(0,n):
e=int(input("enter the elements"))
a.append(e)
x=int(input("enter element to search"))
search(a,x)

Binary search
def binary_search(item_list,item):
first = 0
last = len(item_list)-1
found = False
while( first<=last and not found):
mid = (first + last)//2
if item_list[mid] == item :
found = True
36

else:
if item <item_list[mid]:
last = mid - 1
else:
first = mid + 1
return found
list_val=list(input(―Enter the values of the list‖)) #enter values one by one separated by ,
search=int(input(―Enter the value to search‖))
print(binary_search(list_val,search))

Additional programs
1. Python program to find the factorial of a number provided by the user.
num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num< 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

2. Python program to find the factorial of a number using recursion.


def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = int(input("Enter a number: "))
# check is the number is negative
if num< 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",recur_factorial(num))

3. Python program to find the largest number among the three input numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
if (num1 >= num2) and (num1 >= num3):
37

largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number between",num1,",",num2,"and",num3,"is",largest)

4. Python program to check if the input number is prime or not


num = int(input("Enter a number: "))
#prime numbers are greater than 1
if num> 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
# if input number is less thanor equal to 1, it is not prime
else:
print(num,"is not a prime number")

5. Program to display the Fibonacci sequence up to n-th term


nterms = int(input("How many terms? "))
# first two terms
n1 = 0
n2 = 1
count = 0
# check if the number of terms is valid
if nterms<= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while count <nterms:
print(n1,end=' , ')
nth = n1 + n2
# update values
n1 = n2
n2 = nth count += 1
38

6. Python Program to Check Armstrong


num =(input("Enter first number: "))
#Changed num variable to string, and calculated the length (number of digits)
order = len(str(num))
#initialize sum
sum = 0
#find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
#display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

7. Python program to check if the input number is odd or even.


#A number is even if division by 2 give a remainder of 0.
#If remainder is 1, it is odd number.
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))

8. Program to add two matrices using nested loop


X = [[12,7,3],[4 ,5,6],[7 ,8,9]]
Y = [[5,8,1],[6,7,3],[4,5,9]]
result = [[0,0,0],[0,0,0],[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)
9. Program to multiply two matrices using nested loops
# 3x3 matrix
X = [[12,7,3], [4 ,5,6],[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]]
result = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]

Mr. P. J. Merbin Jose


39

# iterate through rows of X


for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
10. Program to transpose a matrix using nested loop
X = [[12,7], [4 ,5], [3 ,8]]
result = [[0,0,0], [0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]
for r in result:
print(r)

11. Program to sort alphabetically the words from a string provided by the user
my_str = input("Enter a string: ")
wordswords = my_str.split() #breakdown the string into a list of
# words.sort() #sort the list
# display the sorted words
print("The sorted words are:")
for word in words:
print(word)

12. Python Program to Count the Number of Vowels Present in a String

s=raw_input("Enter string:")
count = 0
vowels = ['a','e','i','o','u']
for letter in s:
if letter in vowels:
count += 1
print("Count of the vowels is:")
print(count)
Output
Enter string: hello welcome
Count of the vowels is:
5
Explanation
raw_input: raw_input() takes exactly what the user typed and passes it back as a string.
input() first takes the raw_input() and then performs an eval() on it as well.

Mr. P. J. Merbin Jose


40

Part A:
1. What are Boolean values?
2. Define operator and operand?
3. Write the syntax for if with example?
4. Write the syntax and flowchart for if else.
5. Write the syntax and flowchart for chained if.
6. Define state
7. Write the syntax for while loop with flowchart.
8. Write the syntax for for loop with flowchart.
9. Differentiate break and continue.
10. Mention the use of pass
11. What is fruitful function
12. What is void function
13. Mention the different ways of writing return statement
14. What is parameter and list down its type?
15. What is local and global scope?
16. Differentiate local and global variable?
17. What is function composition, give an example?
18. Define recursion.
19. Differentiate iteration and recursion.
20. Define string. How to get a string at run time.
21. What is slicing? Give an example.
22. What is immutability of string?
23. List out some string built in function with example?
24. Define string module?
25. How can list act as array?
Part B:
1. Explain conditional statements in detail with example(if, if..else, if..elif..else)
2. explain in detail about operators in detail
3. Explain in detail about iterations with example.(for, while)
4. Explain in detail about string built in function with suitable examples?
5. Explain about loop control statement(break, continue, pass)
6. Briefly discuss fruitful function.
7. Discuss with an example about local and global variable and function composition
8. Explain in detail about recursion with example.
9. Explain in detail about strings and its operations(slicing,immutablity)
10. program to search an element using linear search.
11. program to search an element using binary element.
12. program to find factorial of a given number using recursion

Mr. P. J. Merbin Jose

You might also like