Sei sulla pagina 1di 34

[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

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 BOOLEAN VALUES AND OPERATORS:


 The Python type for storing true and false values is called bool,
 There are only two boolean values. They are True and False.
 Capitalization is important, since true and false are not boolean values 

3.1.1 Boolean expressions


 A boolean expression is an expression that is either true or false.
 The following examples use the operator ==, which compares two operands and
produces True if they are equal and False otherwise:
 Example:
>>> 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'>
 The == operator is one of the relational operators; the others are:
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

PPG INSTITUTE OF TECHNOLOGY Page 1


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

3.1.2 Logical operators


 There are three logical operators that are used to compare values.
 They evaluate expressions down to Boolean values, returning either True or False.
 These operators are and, or, and not which are defined in the table below.
Example
Operator Description
x=True , y=False
and True if both are true x and y returns False
or True if at least one is true x or y returns True
not True only if false not x returns False

3.2 DECISION MAKING STATEMENTS:


 Decision-making is the anticipation of conditions occurring during the execution of a
program and specified actions taken according to the conditions.
 Decision structures evaluate multiple expressions, which produce True or False as the
outcome.
 We need to determine which action to take and which statements to execute if the
outcome is True or False otherwise.
 Types of Conditional Statements:
 if statements (Conditional)
 if-else statements (Alternative)
 if-elif-else (Chained conditional)
 Nested conditional

3.2.1 Conditional if:


 The if statement contains a logical expression using which the data is compared and a
decision is made based on the result of the comparison.
 Syntax
if expression:
statement(s)
 If the boolean expression evaluates to True, then the block of statement(s) inside the
if statement is executed. 
 If boolean expression evaluates to False, then the first set of code after the end of
block is executed.

PPG INSTITUTE OF TECHNOLOGY Page 2


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 Flowchart

 Example:
a=10
if a>9:
print(“a is Greater than 9”)
 Output:
a is Greater than 9

3.2.2 if… Else Statements:


 The if-else statement is a 2 way decision making statement
 It is used to execute some statements when the condition is true and execute some
other statements, when the condition is false
 Syntax:
if expression:
statement(s)
else:
statements(s)
 Flowchart:

PPG INSTITUTE OF TECHNOLOGY Page 3


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 Example:
a=10
b=20
if a>b:
print(“a greater than b”)
else:
print(“b is greater than a”)

 Output:
b is greater than a

3.2.3 if-elif-else (Chained Conditional)


 The if-elif-else statement allows us to check multiple conditions and execute a block
of code whose condition evaluates to True.
 Syntax:
if expression1:
statement1
elif expression2:
statement2
elif expression3:
statement3
else:
statement4

PPG INSTITUTE OF TECHNOLOGY Page 4


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 Flowchart:

F
expressio
n1
T F

statement1 expressio
n2
T F
statement2 expressio
n3
T

statement3 statement4

 Example: Greatest of 3 numbers


a=10
b=50
c=6
if (a>b) and (a>c):
print(“a is greatest”)
elif (b>a) and (b>c):
print(“b is greatest”)
else:
print(“c is greatest”)

 Output:
b is greatest

3.2.4 Nested Conditionals:


 A conditional statement can be placed within another conditional statement. This
types of statement is called nested conditionals.
 Any number of conditional statements can be nested inside one another
 Syntax
PPG INSTITUTE OF TECHNOLOGY Page 5
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

if(condition 1):
if(condition 2):
True statement 2
else:
False statement 2
else:
False statement 1
 Flowchart

F
Condition
1

T False statement 1

T
F
Condition
2

True Statement 2 False Statement 2

 Example:
x=10
y=20
if x == y:
print('x and y are equal')
else:
if x < y:
PPG INSTITUTE OF TECHNOLOGY Page 6
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

print('x is less than y')


else:
print('x is greater than y')

 Output:
x is less than y

3.3 ITERATION:
 Iteration/Looping is defined as the block of statements which are repeatedly executed
for certain number of times or until a particular condition is satisfied.
 Types of Iteration/Looping:
 While loop
 For loop
 Nested loop
3.3.1 While loop
 It is a repetitive control structure, used to execute the statements within the body,
until the condition satisfies.
 The while loop is an entry controlled loop statement, which means the condition is
evaluated first and if it is true, then the body of the loop is executed.
 Syntax:
while( condition):
body of the loop

 Flow Chart:

F
conditio
n

Body of the loop

PPG INSTITUTE OF TECHNOLOGY Page 7


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 Example: While Loop Statement


x=0
while (x < 5):
print(x)
x += 1
 Output:
01234

3.3.2 The for loop


 The for loop is another repetitive control structure, and is used to execute a set of
instructions repeatedly, until the condition becomes false.
 Syntax:
for <variable> in <sequence>:
<statements>

 Flowchart

If no more item in
sequence
Items in
sequenc
e
Next item from
sequence

Statements

PPG INSTITUTE OF TECHNOLOGY Page 8


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

Example 1: Printing characters in a word using for loop.


for word in 'python':
print('char in word:',word)
Output:
char in word: p
char in word: y
char in word: t
char in word: h
char in word: o
char in word: n

Example 2: Addition of number upto 10 by using the for loop


sum=0
for i in range(11):
sum =sum+i
print('Sum of the first 10 numbers:',sum)
Output:
Sum of the first 10 numbers: 55

Example 3: Program to print weekdays using for loop


days=['monday','tuesday','wednesday','thursday','friday','saturday','sunday']
for days in days:
print('week day:',days)
Output:
week day: monday
week day: tuesday
week day: wednesday
week day: thursday
week day: friday
week day: saturday
PPG INSTITUTE OF TECHNOLOGY Page 9
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

week day: Sunday

3.3.3 Nested Loop


 The process of placing a loop inside another loop is called Nested loop.
 We can put any type of loop inside any other type of loop. For example a for loop can
be inside a while loop or vice versa.
 Syntax:
while exp1:
while exp2:
statement1
statement2
Example:
a=0
b=0
while a < 4:
a=a+1
while b < 4:
b=b+1
print(a, b)

Output:
1 1
1 2
1 3
1 4

3.3.4 Using else statement with loops:


 Python supports to have an else statement associated with a loop statement.
 If the else statement is used with a for loop, the else statement is executed
when the loop has exhausted iterating the list.
 If the else statement is used with a while loop, the else statement is executed
when the condition becomes false.
 Python: while and else statement
PPG INSTITUTE OF TECHNOLOGY Page 10
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

Syntax:
while(expression):
statement_1
statement_2
......
else:
   statement_3
    statement_4
    ......
Example 1: Program to illustrate the else in while loop
count = 0

while count < 5:

print (count, " is less than 5")

count = count + 1

else:

print (count, " is not less than 5")

Output:

0 is less than 5

1 is less than 5

2 is less than 5

3 is less than 5

4 is less than 5

5 is not less than 5

Example 2: For loop with else


for i in range(5):
print(i)
else:

PPG INSTITUTE OF TECHNOLOGY Page 11


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

print(“Iteration Over”)

Output:
0
1
2
3
4
Iteration Over

3.3.5 Loop Control Statements


 Loop control statements change execution from its normal sequence.
 Python supports the following control statements.

Control Statement Description

break statement Terminates the loop and continue with the


statement following the loop

continue statement Continue with the next iteration of the loop by


skipping its remaining body of the loop

pass statement It is a statement which does not perform any


operation. (Do-Nothing)

3.3.5.1 Python break statement


 Break statement is used to terminates the loop and continue with the statement
following the loop
 If break statement is inside a nested loop (loop inside another loop), break will
terminate the innermost loop alone.
 Syntax:
break
PPG INSTITUTE OF TECHNOLOGY Page 12
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

Flowchart of break

Example: Python break


for val in "string":
if val == "i":
break
print(val)
print("The end")

Output:
s
t
r
The end
3.3.5.2 Python continue statement
 It is used to continue with the next iteration of the loop by skipping its remaining
body of the loop
 Syntax:
continue
Flowchart of continue 

PPG INSTITUTE OF TECHNOLOGY Page 13


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

Example: Python continue


for val in "string":
if val == "i":
continue
print(val)
print("The end")

Output:
s
t
r
n
g
The end

3.3.5.3 Python Pass Statement

 It is a statement which does not perform any operation.


 Pass is a null statement.
 The difference between a comment and pass statement in Python is that, while the
interpreter ignores a comment entirely, pass is not ignored.
 Syntax of pass
pass
PPG INSTITUTE OF TECHNOLOGY Page 14
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

Example: pass Statement


for i in 'Python':
if i=='h':
pass
print("This is pass block")
print("Current Letter:",i)
print("END")
Output:
Current Letter: P
Current Letter: y
Current Letter: t
This is pass block
Current Letter: h
Current Letter: o
Current Letter: n
END

3.3.5.4 Difference between break and continue statement

break continue
Terminates the loop Continue with the next iteration of the loop
Syntax: Syntax:
break continue
Exits the loop It never terminates the loop

3.4 FRUITFUL FUNCTIONS

 A fruitful function is a function that returns a value when it is called.

 Most of the builtin functions that we have used are fruitful.

 Ex: pow,abs,sqrt

3.4.1 Return value

 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.

PPG INSTITUTE OF TECHNOLOGY Page 15


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 Ex:
e = math.exp(1.0)
 Example for a fruitful function:
def area(radius):
a = math.pi * radius**2
return a
 In the above example, the function returns a value. It is also possible to include an
expression in the return statement as follows.
 Example:
def area(radius):
return math.pi * radius**2
 Sometimes it is useful to have multiple return statements, one in each branch of a
conditional as follows:

def absolute_value(x):
if x < 0:
return -x
else:
return x
 Since these return statements are in an alternative conditional, only one runs.
 As soon as a return statement runs, the function terminates without executing any
subsequent statements.
 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.
 For example:
def absolute_value(x):
if x < 0:
return -x
if x > 0:
return x

PPG INSTITUTE OF TECHNOLOGY Page 16


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 This function is incorrect because if x happens to be 0, neither condition is true, and


the function ends without hitting a return statement.

3.4.2 Parameters:
 When a function is invoked, a value is passed to the parameter. This value is referred
to as actual parameter or argument. Parameters provide the data communication
between calling function and called function.
 Two types:
 Actual parameters:
These are the parameters transferred from the calling function [main function]
to the called function [user defined function].
 Formal parameters:
Passing the parameters from the called functions [user defined function] to the
calling functions [main function].
Note:
 Actual parameter – This is the argument which is used in function call.
 Formal parameter – This is the argument which is used in function definition.

3.4.3 Scope Of Variables


 All variables in a program may not be accessible at all locations in that program.
 This depends on where we have declared a variable.
 The scope of a variable determines the portion of the program where we can access a
particular identifier.
 There are two basic scopes of variables in Python −
 Global variables
 Local variables

3.4.3.1 Global and Local variables


Local Variables Global Variables
Variables are defined inside a function Variables are defined outside of any
body function
Local variables can be accessed only Global variables can be accessed
inside the function in which they are throughout the program body by all

PPG INSTITUTE OF TECHNOLOGY Page 17


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

declared functions.
Local variables exist within functions. Global Variables exist outside of functions.

 Example 1: Printing global variable outside the function


glb_var = "global"
def var_function():
lcl_var = "local"
print(lcl_var)
var_function()
print(glb_var)
Output
local
global
 Example 2: Printing global variable inside and outside the function
glb_var = "global"
def var_function():
lcl_var = "local"
print(lcl_var)
print(glb_var)
var_function()
print(glb_var)
Output
local
global
global

 Let’s look at another example where we use the same variable name for a global
variable and a local variable:
num1 = 5
def my_function():
num1 = 10
num2 = 7
print(num1)

PPG INSTITUTE OF TECHNOLOGY Page 18


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

print(num2)
my_function()
print(num1)

Output
10
7
5
 Inside the function num1 has the value 10 since it is locally assigned and outside the
function num1 has the value 5 since it has global value.
 We can create a global variables within a function by using Python’s global statement
as follows:
def new_shark():
global shark
shark = "Sammy"
new_shark()
print(shark)
Output:
Sammy

3.4.4 Function Composition


 We can call one function from within another. This ability is called composition.
 As an example, we’ll write a function that takes two points, the center of the circle
and a point on the perimeter, and computes the area of the circle.
 Assume, the center point is xc and yc, and the perimeter point is xp and yp.
 The first step is to find the radius of the circle, which is the distance between the two
points.
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
result = math.sqrt(dsquared)
return result
PPG INSTITUTE OF TECHNOLOGY Page 19
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

radius = distance(xc, yc, xp, yp)


 The next step is to find the area of a circle with that radius
def area(radius):
    a = math.pi * radius**2
    return a
result = area(radius)
 Encapsulating these steps in a function, we get:
def circle_area(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result
 We can make it in a easier way by composing the function calls as follows:
def circle_area(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp))
 Example:
import math
def distance(x1,y1,x2,y2):
return math.sqrt((x1-x2)**2+(y1-y2)**2)
def area(r):
return 3.14*r**2
print("Area of Circle=",area(distance(3,0,4,0)))
 Output:
Area of Circle=3.14
3.4.5 Boolean functions
 Functions can return booleans, which is often convenient for hiding complicated tests
inside functions.
 For example:
def is_divisible(x, y):
if x % y == 0:
return True
else:
return False
 Here is an example:
PPG INSTITUTE OF TECHNOLOGY Page 20
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

>>> is_divisible(6, 4)
False
>>> is_divisible(6, 3)
True
 The result of the == operator is a boolean, so we can write the function more
concisely by returning it directly:
def is_divisible(x, y):
return x % y == 0
 Boolean functions are often used in conditional statements:
if is_divisible(x, y):
print 'x is divisible by y'

3.4.6 Recursion:
 A function that calls itself is recursive; the process of executing it is called
recursion.
Computing the factorial of a number using recursion
 The factorial of an integer n, which is written as n!, is the result of multiplying n by
all of the positive integers less than n. For instance, 3! = 3 x 2 x 1, which results in 6
and 4! = 4 x 3 x 2 x 1, which results in 24.
 An efficient way to calculate a factorial is by using a recursive function.
 

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input())
print(factorial(n))
 

PPG INSTITUTE OF TECHNOLOGY Page 21


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

Advantages of Recursive Functions:


 Recursion can produce simpler, more natural solutions to a problem
 It is written with less number of statements
 Recursive functions are effective where the terms are generated successively to
compute a value
 It requires few variables which makes program clean
 It is useful for branching processes
 
Disdvantages:
 Recursive solution is always logical and it is very difficult to trace.(debug and
understand).
 In recursive we must have an if statement somewhere to force the function to return
without the recursive call being executed, otherwise the function will never return.
 Recursion takes a lot of stack space, usually not considerable when the program is
small and running on a PC.
 Recursion uses more processor time.

Difference between recursion and iteration


Recursion Iteration
Repetition is achieved through repeated Iteration is explicitly a repetition structure
function calls
Recursion terminates when a base case is Iteration terminates when the loop
recognized continuation test become false
Recursion causes an Iteration normally occurs within a loop,
other copy of the function and hence a so the extra memory assignment is

PPG INSTITUTE OF TECHNOLOGY Page 22


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

considerable memory space is occupied. omitted

3.5 STRINGS
 A String is a sequence of characters .i.e they can be a letter, a number, special
symbols or combination of these types.
 Python permits to represent the string either by using single or double quote.
 Python strings are “immutable” which means they cannot be changed after they are
created.
 Example :
>>>str= “Hello Python”
>>>print(str)
Hello Python
 We can access the characters one at a time using bracket operator.
>>>letter=fruit[1]
 It selects character number 1 from fruit and assigns it to a letter.
 The expression in brackets is called an index.
 The index indicates which character in the sequence we need.
 An index may be expressions that contain variables and operators.
>>>fruit=`banana`
>>>i=1
>>>fruit[i]
`a`
>>>fruit[i+1]
`n`
 But the value of the index has to be an integer.
>>>letter=fruit[1.5]
TypeError:String indices must be integers.
 len:
len is a built-in function that returns the number of characters in a string:
>>>fruit=`banana`
>>>len(fruit)
6
 To get the last character, we have to subtract from length.

PPG INSTITUTE OF TECHNOLOGY Page 23


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

>>>last=fruit[length-1]
>>>last
`a`
>>>last=fruit[length]
IndexError:string index out of range
 The reason for IndexError is that there is no letter in ‘banana’ with index 6 since the
count starts from 0, the six letters are numbered as 0 to 5.
>>>fruit[-1] which yields the last character.

B A N A N A
0 1 2 3 4 5 6
-7 -6 -5 -4 -3 -2 -1
 Example:
Fruit=”banana”
print(fruit[0]) #return 1st character
#output:b
print(fruit[-1]) #return last character
#output:a
print(fruit[-2]) #return last second character
#output:n
3.5.1 String Slices:
 To retrieve a range of characters in a String we use “Slicing Operator”, the colon
“:”
 With the slicing operator, we define the range as [a:b]. It’ll let us print all the
characters of the String starting from index ‘a’ up to character at index ‘b-1’.
 So the character at index ‘b’ is not a part of the output.
 Example:
sample_str = 'Python String'
print (sample_str[3:5])     
print (sample_str[7:])      
print (sample_str[:6])      
print (sample_str[7:-4])
Output

PPG INSTITUTE OF TECHNOLOGY Page 24


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

ho
String
Python
St

3.5.2 Modifying/Deleting Strings:


 Python Strings are by design immutable.
 It suggests that once a String binds to a variable; it can’t be modified.
 If we want to update the String simply re-assign a new String value to the same
variable.
 Example 1:
>>>sample_str = 'Python String'
>>>sample_str[2] = 'a'
  # TypeError: 'str' object does not support item assignment
 
 The best way to change is create a new string that is a variation on the original:
>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> new_greeting
'Jello, world!'
 This example concatenates a new first letter onto a slice of greeting . It has no effect
on the original string.

3.5.3 String Comparison:


 The comparison operations work on string to see if two strings are equal:
 Example:
word="Python"
if (word=="Python"):
print("Both Strings are equal")
Output:
Both Strings are equal

3.5.4 Escape Characters

PPG INSTITUTE OF TECHNOLOGY Page 25


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 An escape character gets interpreted; in a single quoted as well as double quoted


strings.
 These are special characters that are not displayed on the screen; rather they control
the display of output.
 Following table is a list of escape or non-printable characters that can be
represented with backslash notation.
Escape Description Example Output
Sequence
\\ Prints Backslash print(“\\”) \
\’ Prints Single-quote print(“\’”) ‘
\” Prints double quote print(“\””) “
\a ASCII bell makes bell print(“\a”) Bell Sound
sound
\b ASCII backspace removes print(“ab”+”\b”+”c”) ac
previous characters
\f ASCII form feed print(“hello\fworld”) Hello
world
\n ASCII line feed print(“hello\nworld”) Hello
world
\r ASCII Carriage print("Hello \r World!") Hello
returns(CR) World!
\t ASCII horizontal tab print(“\thello”) hello
\v ASCII vertical tab print(“\vhello”)
hello
\ooo Character with Octal Value print("\110\145\154\154\1 Hello
ooo 57\40\127\157\162\154\14 World !
4\41")
\xhh Character with Hex Value print("\x48\x65\x6c\x6c\x Hello
hh 6f\x20\x57\x6f\x72\x6c\x World !
64\x21")

3.5.5 String Special Operators


Assume string variable a holds 'Hello' and variable b holds 'Python', then −
Operato Description Example
r
+ Concatenation - Adds values a + b will give
on either side of the operator HelloPython

PPG INSTITUTE OF TECHNOLOGY Page 26


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

* Repetition - Creates new a*2 will give


strings, concatenating -HelloHello
multiple copies of the same
string
[] Slice - Gives the character a[1] will give e
from the given index
[:] Range Slice - Gives the a[1:4] will give ell
characters from the given
range
in Membership - Returns true if H in a will give 1
a character exists in the given
string
not in Membership - Returns true if M not in a will give
a character does not exist in 1
the given string
r/R Raw String - Suppresses print r'\n' prints \n
actual meaning of Escape and print
characters. The "r" can be R'\n'prints \n
lowercase (r) or uppercase
(R) and must be placed
immediately preceding the
first quote mark.

3.6 STRING FUNCTIONS AND METHODS:


S String Description Example
No. Method
The method upper takes a >>> word = 'banana'

upper() string and returns a new string >>>new_word = word.upper()


1 with all uppercase letters. >>> new_word
'BANANA'

The method lower takes a >>> word = 'BANANA'


lower() string and returns a new string >>> new_word = word.lower()
2
with all lowercase letters. >>> new_word
'banana'
3 find() The method find search for a >>> index = word.find('a')

PPG INSTITUTE OF TECHNOLOGY Page 27


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

specific character or characters >>> index


in a string. 1
>>> word.find('na')
2
By default, find starts at the >>> word = 'banana'
beginning of the string, but it >>> word.find('na', 3)
can take a second argument, 4
the index where it should start:
The method count adds up the >>> s = "The the"
count() number of times a character or >>> s.count("t")
4
sequence of characters appears 1
in a string.
Capitalizes first letter of string >>> s=”west”
capitalize() >>>new_s = s.capitalize()
5
>>>new_s
West
The method isalnum() checks >>> s='sadsaf12412'
isalnum()
6 whether the string consists of >>> print(s.isalnum())
alphanumeric characters. True
Returns true if string has at >>> s="dhghg66"
isalpha() least 1 character and all >>> print(s.isalpha())
7
characters are alphabetic and False
false otherwise
It is used to determine the size >>>s=”Python”
8 len() of a string that is, the number >>>len(s)
of characters in a string 6
The index() method >>>str1=”String string String
determines if the string str string String”
occurs in string or in a >>>print(str1.index(“String”,3))
9 index()
substring of string, if the
starting index ending index
are given.
10 endswith() It returns True if the string >>>str1=”String string String
ends with the specified suffix, string String”
otherwise return False  >>>print(str1.endswith(“String”))

PPG INSTITUTE OF TECHNOLOGY Page 28


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

True
>>>print(str1.endswith(“String”,0,
27))
False
Returns true if string contains >>>str1=”StringString3”
only digits and false >>>str2=”4567”
otherwise. >>>print(str1.isdigit())
11 isdigit()
False
>>>print(str2.isdigit())
True
This method will return a title >>>str1=”string string string”
case version of the given >>>print(str1.title())
string, where the first letter of String String String
12 title()
a word is in uppercase and the
rest of the characters in the
lower case
This method will return true, >>>str1=” “
if the given string contains >>>print(str1.isspace())
13 isspace
only whitespace characters True
and false otherwise
This method will return true, >>>str1=”String String”
if the given string is a title >>>print(str1.istitle())
14 istitle() cased string and it should True
have at least one character
and false otherwise
This method will return true, >>>str1=”String String”
15 isupper() if all the characters in >>>print(str1.isupper())
uppercase and false otherwise True
This method will return true, >>>str1=”String String”
16 islower if all the characters in >>>print(str1.islower())
lowercase and false otherwise False

3.7 STRING MODULE:


 The String module contains a number of useful constants and classes and various
functions for handling strings

PPG INSTITUTE OF TECHNOLOGY Page 29


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 Many string module functions are also available as string object methods.
 This module contains constants for a number of frequently used collection of
characters.
 Example for constants:
import string
print(string.digits)
print(string.hexdigits)
print(string.octdigits)
print(string.punctuation)
print(string.whitespace)
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
 Output:
0123456789
0123456789abcdefABCDEF
01234567
!”#$%&’()*+,-./:;?@[\]^_’{|}`
‘\011\012\013\014\015’
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ

 Example 2: Functions
import string
text="Monty Python's Flying Circus"
print(string.upper(text))
print(string.lower(text))
print(string.split(text))
print(string.join(string.split(text), "+"))
print(string.replace(text, "Python", "Java"))
print(string.find(text, "Python"), string.find(text, "Java"))
print(string.count(text, "i"))
PPG INSTITUTE OF TECHNOLOGY Page 30
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 Output:
MONTY PYTHON'S FLYING CIRCUS
monty python's flying circus
['Monty', "Python's", 'Flying', 'Circus']
Monty+Python's+Flying+Circus
Monty Java's Flying Circus
(6, -1)
2
3.8 ILLUSTRATIVE PROBLEMS:
1. Square root of a number
def newtonSqrt(n, howmany):
approx = 0.5 * n
for i in range(howmany):
betterapprox = 0.5 * (approx + n/approx)
approx = betterapprox
return betterapprox
print(newtonSqrt(10, 3))
print(newtonSqrt(10, 5))
print(newtonSqrt(10, 10))

Output:
3.16231942215
3.16227766017
3.16227766017

2. GCD of two numbers


n1=int(input("Enter a Number"))
n2=int(input("Enter another Number"))
rem=n1%n2
while rem!=0:
n1=n2
n2=rem
rem=n1%n2
PPG INSTITUTE OF TECHNOLOGY Page 31
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

print ("GCD of given numbers is:",n2)


Output:
Enter a Number 54
Enter another Number 45
GCD of given numbers is: 9

3. Exponentiation
n=int(input("Enter a number :"))
p=int(input("Enter its power :"))
pow=1
for i in range(1,p+1):
pow=pow*n
print (pow)

Output:
Enter a number :2
Enter its power :3
8

4. Sum an array of numbers


def listsum(numList):
if len(numList) == 1:
return numList[0]
else:
return numList[0] + listsum(numList[1:])
print("Sum of array numbers :",(listsum([1,3,5,7,9])))
Output
Sum of array numbers : 25

5. Linear search
def linearSearch(myList, searchColour):
flag=0

PPG INSTITUTE OF TECHNOLOGY Page 32


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

for i in range(len(myList)):
if myList[i] == searchColour:
flag=1
break
if flag:
print("Color is found at index", i)
else:
print("Color is not found at index")
myList = ['Red', 'Blue', 'Yellow', 'White', 'Black']
searchColour = input("Enter a Color:")
linearSearch(myList, searchColour)

Output
Enter a Color: Red
Color is found at index 0

6. Binary Search
myList = [5, 10, 12, 24, 34, 47, 54]
def binarySearch(myList, searchNum):
firstNum = 0
lastNum = len(myList)-1
result = False
while(result == False and firstNum <= lastNum):
midNum = (firstNum + lastNum)//2
if myList[midNum] == searchNum:
result = True
else:
if searchNum < myList[midNum]:
lastNum = midNum - 1
else:
firstNum = midNum + 1
return result
searchNum = (int(input("Enter the number to be search")))
PPG INSTITUTE OF TECHNOLOGY Page 33
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

output = binarySearch(myList, searchNum)


if output:
print("Number found and the number is: ", searchNum)
else:
print("Number not found")

Output:
Enter the number to be search 12
Number found and the number is: 12

PPG INSTITUTE OF TECHNOLOGY Page 34

Potrebbero piacerti anche