0% found this document useful (0 votes)
13 views34 pages

23CS101T PSPP - Unit 3

The document discusses various control flow statements in Python including conditionals like if, if-else and if-elif-else statements. It also covers iterative statements like while and for loops along with examples. Functions in Python are explained with concepts like parameters, return values, local and global scopes.

Uploaded by

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

23CS101T PSPP - Unit 3

The document discusses various control flow statements in Python including conditionals like if, if-else and if-elif-else statements. It also covers iterative statements like while and for loops along with examples. Functions in Python are explained with concepts like parameters, return values, local and global scopes.

Uploaded by

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

23CS101T PSPP

UNIT-III CONTROL FLOW, FUNCTIONS, STRINGS


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 alices, immutablity, string functions and methods, string module; List as arrays.
Illustrative program : Square root, gcd, exponentiation, sum an array of numbers, linear search,
binary search

3.1 CONDITIONALS:
Boolean values:
 Boolean values are the two constant objects False and True. They are used to represent truth
values (although other values can also be considered false or true). In numeric contexts (for
example when used as the argument to an arithmetic operator), they behave like the integers
0 and 1, respectively.
 A string in Python can be tested for truth value.
 The return type will be in Boolean value (True or False)
 To see what the return value (True or False) will be, simply print it out.

str="Hello World"

print(str.isalnum()) #False #check if all char are numbers

print( str.isalpha()) #False #check if all char in the string are alphabetic

print(str.isdigit()) #False #test if string contains digits

print(str.istitle()) #True #test if string contains title words

print(str.isupper()) #False #test if string contains upper case

print (str.islower()) #False #test if string contains lower case

print (str.isspace()) #False #test if string contains spaces

3.2 INTRODUCTION TO DECISION CONTROL STATEMENTS:


A statement that determines the control flow of a setof instructions. i.e., it decides the sequence in
which the instructions in a program are executed.
The three fundamental methods of control flow in a programming language are:
• Sequential Control: A Python program is executed sequentially fromthe first line of the
program to its last line.
• Selection Control: To execute only a selected set of statements.
• Iterative Control: To execute a set of statements repeatedly.

SELECTION/CONDITIONAL BRANCHING STATEMENT:


The decision control control statements usually jumps from one part of the code to the another
depending on whether a particular condition is satisfied or not. The statements are executed based on
certain decisions which is known as selection control statements or conditional branching statements.
Python language supports different types of conditional branching statementswhich are as follows:
 If statement
 If-Else statement
 Nested if statement
 If-elif-else statement

Condiotional If Statement:

 An if statement is a selection control statement based on the value of agiven Boolean expression.
 The if structure may include 1 statements or n statements enclosed withinthe if block.
 First the test expression is evaluated. If the test expression is true , the statements of if block are
executed, otherwise these statements will beskipped and the execution will jump to statement X.

Alternative( If-else ) statement:

 First the test expression is evaluated.


 If the expression is True, statement block 1 is executed and statementblock 2 is skipped.
 Otherwise , if the expression is false statement block 2 is executed andstatement block 1 is
ignored.
Nested if statement:

 A statement that contains other statements is called a compoundstatement.


 To perform more complex checks, if statements can be nested, that is, itcan be placed one inside
the other.
 In such a case, the inner if statement is the statement part of the outer one.Nested if statements
are used to check if more than one conditions are satisfied.

Chained conditional ( If-elif-else) statement:

 Python supports if-elif-else statements to test additional conditions apartfrom the initial test
expression.
 The if-elif-else construct works in the same way as a usual if-else statement. If-elif-else construct
is also known as nested-if construct.
3.3 ITERATIVE STATEMENTS:
Iterative statements are decision controlstatements that are used to
repeat the execution of a list of statements.
Python language supports two types of iterative statements as follows:
• While loop
• For loop
While loop:
The while loop provides a mechanism to repeat one or more statements while a particular condition is
true.
For loop:
For loop provides a mechanism to repeat a task until a particular condition isTrue. It is usually known as
a determinate or definite loop because the programmer knows exactly how many times the loop will
repeat.
The for...in statement is a looping statement used in Python to iterate over asequence of objects.

Syntax:
for iterating_var in sequence:
statements(s)

If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is
assigned to the iterating variable iterating_var. Next, the statements block is executed. Each item in the list
is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted.
Flow Chart :

list = [10,30,23,43,65,12]
sum = 0
for i in list:
sum = sum+i
print("The sum is:",sum)

OUTPUT
The sum is: 183
The Range() function:

 The range() function is a built-in function in Python that is used to iterate over a sequence of
numbers.
 The syntax of range() : range(beg, end, [step])
 The range() produces a sequence of numbers starting with beg (inclusive) and ending with one
less than the number end.
 The step argument is optional
 By default, every number in the range is incremented by 1 but we can specify a different
increment using step.
 It can be both negative and positive, but not zero.

• If range() function is given a single argument, it produces an object with valuesfrom 0 to argument-1.
For example: range(10) is equal to writing range(0, 10).
• If range() is called with two arguments, it produces values from the first to thesecond. For example,
range(0,10).
• If range() has three arguments then the third argument specifies the interval ofthe sequence produced.
In this case, the third argument must be an integer. For example, range(1,20,3).
Examples:

CONDITION CONTROLLED AND COUNTER CONTROLLEDLOOPS:

NESTED LOOPS:

 Loops placed inside other loop is said to be nested loop


 A for loop can be used to control the number of times a particular set ofstatements will be
executed.
 Another outer loop could be used to control the number of times that awhole loop is repeated.
 Loops should be properly indented to identify which statements arecontained within each for
statement.
3.4 The Break Statement:

 The break statement is used to terminate the execution of the nearestenclosing loop in which it
appears.
 When compiler encounters a break statement, the control passes to thestatement that follows the
loop in which the break statement appears.

SYNTAX:break

EXAMPLE:

The Continue Statement:

 The continue statement can only appear in the body of a loop.


 When the compiler encounters a continue statement the rest of the statements in the loop are
skipped and the control is unconditionally transferred to the loop-continuation portion of the
nearest enclosing loop.

SYNTAX:continue
The Pass Statement:

 Pass statement is used when a statement is required syntactically but nocommand or code has to
be executed.
 It specifies a null operation or simply No Operation (NOP) statement.
 It remains the same when the pass statements are executed.
SYNTAX:pass
EXAMPLE:

`THE ELSE STATEMENTS USED WITH LOOPS:

 If the else statement is used with a for loop, the else statement is executedwhen the loop has
completed iterating.
 When the else statement is executed with the while loop, the else
statement is executed when the condition becomes false.
3.5 FUNCTIONS:

 A function is a block of organized and reusable program code that performs a single , specific
and well defined task.
 Python enables its programmers into functions , each of which can bewritten more or less
independently of the others.

Fig a:-) Calling a function

 In the above figure (a), a func1() is called to perform a well-defined tasks.When the func1() is
called , the program control is passed to the first statement in the function.
 All the statements in the functions are executed and then the programcontrol is passed to the
statement following the one that called the function.

Fig b:-) Function calling another function


 In the figure b, func1() calls function named func2(), so func1() is known as the calling function
and func2() is known as the called function.
 When the compiler encounters a function call instead of executing the next statement in the
calling function , the control jumps to the statementthat are a part of the called function.
 After the called function is executed , the control is returned back to thecalling program
 It is not that the func1() can call only one function , it can call as many functions as it wants and
as many times it wants.
 For example, a function call placed within for loop or while loop may call the same function
multiple times until the condition holds true.
NEED FOR FUNCTIONS
• Each function to be written and tested separately.
• Understanding, coding and testing multiple separate functions is far easier Without the use of any
function, then there will be countless lines in the codeand maintaining it will be a big mess.
• Programmers use functions without worrying about their code details. This speeds up program
development, by allowing the programmer to concentrate only on the code that he has to write. Different
programmers working on that project can divide the workload bywriting different functions.
• Like Python libraries, programmers can also make their functions and use them from different point in
the main program or any other program that needsits functionalities.

Fig: Top down approach of solving a problem


FUNCTION TYPES
There are mainly two types of functions.
(i) Built-in functions - The built-in functions are those functions that are pre-defined in Python.
(ii) User-defined functions - The user-defined functions are those define by theuser to perform the
specific task.

BUILT-IN FUNCTIONS:
A function is a group of statements that performs a specific task. Theycan either be user-defined
or already built into python interpreter.
The python interpreter has a number of functions built into it that arealways available.

FUNCTION DESCRIPTION
abs() Returns the absolute value of a number
ascii() Returns a string containing a printable representation ofan object,but
escape the non-ASCII characters

dict() Creates a new dictionary

divmod() Returns a pair of numbers consisting of quotient andremainder when


using integer division

eval() The argument is parsed and evaluated as a pythonexpression

float() Converts a string or a number to floating point

hex() Converts an integer number to a hexadecimal string

len() Returns the length(the number of items) of an object

max() Returns the largest item in an iterable

min() Returns the smallest item in an iterable

pow() Returns power raised to a number

slice() Returns a slice object

range() Returns an iterable sequence

Map() Returns an iterator that applies function to every item of


iterable,yielding the results

Sum() Sums the items of an iterable from left to right and returnsthe total

USER-DEFINED FUNCTIONS
The common terminologies used under functions are listed as follows.
• A function, f that uses another function g, is known as the calling function
and g is known as the called function.
• The inputs that the function takes are known as arguments/parameters.
• When a called function returns some result back to the calling function, it issaid to return that result.
• The calling function may or may not pass parameters to the called function. If the called function
accepts arguments, the calling function will pass parameters,else not.
FUNCTION DEFINITION:
Function blocks starts with the keyword def.
• The keyword is followed by the function name and parentheses (( )).
• After the parentheses a colon (:) is placed.
• Parameters or arguments that the function accept are placed withinparentheses.
• The first statement of a function can be an optional statement - the docstring
describe what the function does.
• The code block within the function is properly indented to form the blockcode.
• A function may have a return[expression] statement. That is, the returnstatement is optional.
• You can assign the function name to a variable. Doing this will allowyou to call same function using
the name of that variable.
The syntax of a function definition can be given as:

def function_name(variable1, variable 2): //function header


Documentation string
Statement block
Return [expression]

EXAMPLE:

FUNCTION CALL:
The function call statement invokes the function.
When a function is invoked the program control jumps to the calledfunction to execute the
statements that are a part of that function.
Once the called function is executed, the program control passes back tothe calling function.
The syntax of calling a function that does not accept parameters is simplythe name of the
function followed by parenthesis which is given as,

function_name()
Function call statement has the following syntax when it acceptsparameters.

Example : Program to demonstrate the mismatch between functionparameters and arguments


3.6 FUNCTION PARAMETERS
A function can take parameters which are nothing but some values that are passed to it so that
the function can manipulate them to produce thedesired result.
These parameters are normal variables with a small difference that thevalues of these variables
are defined (initialized) when we call the function and are then passed to the function.
Function name and the number and type of arguments in the function callmust be same as that
given in the function definition.
If the data type of the argument passed does not matches with thatexpected in function then an
error is generated.

PASSING PARAMETERS:
A function can be called by using the following type of formal arguments.

 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments
REQUIRED ARGUMENTS:
In the required arguments, the arguments are passed to a function incorrect positional order.
Also, the number of arguments in the function call should exactly match with the number of
arguments specified in the function definition
KEYWORD ARGUMENTS:
When we call a function with some values, the values are assigned to thearguments based on
their position.
Python also allow functions to be called using keyword arguments inwhich the order (or
position) of the arguments can be changed.
The values are not assigned to arguments according to their position butbased on their name (or
keyword).
Keyword arguments are beneficial in two cases.

1. First, if you skip arguments.


2. Second, if in the function call you change the order of parameters.

Example:-)Program to demonstrate keyword arguments

def display(name,age,salary):
print("name :",name)
print("age :",age)
print("salary :",salary)
n="xyx"
a=30
s=123456
display(salary=s , name=n , age=a)

OUTPUT:
name : xyx
age : 30
salary : 123456

Example: Keyword arguments using assignment operator


DEFAULT ARGUMENTS:
Python allows users to specify function arguments that can have defaultvalues. This means that a
function can be called with fewer arguments than it is defined to have.
That is, if the function accepts three parameters, but function call provides only two arguments,
then the third parameter will be assignedthe default (already specified) value.
The default value to an argument is provided by using the assignmentoperator (=). Users can
specify a default value for one or more arguments.

Example: Default arguments


VARIABLE-LENGTH ARGUMENTS
In some situations, it is not known in advance how many arguments willbe passed to a function.
In such cases, Python allows programmers to make function calls with arbitrary (or any) number
of arguments.
When we use arbitrary arguments or variable length arguments, then the
function definition use an asterisk (*) before the parameter name.
The syntax for a function using variable arguments can be given as,
FRUITFULL FUNCTIONS:
A function that returns a value is called fruitful function.
Example:

def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)

OUTPUT:
30

3.7 RETURN STATEMENTS:


The python return statement is a special statement that is used inside a functionor method to send the
functions result back to the caller.
A return statement consists of a return keyword followed by an optional returnvalue.
The return value of a python function can be any python objectThe syntax of return statement is,

return[expression]

The expression is written in brackets because it is optional.


If the expression is present, it is evaluated and the resultant value is returned to the calling
function. However, if no expression is specifiedthen the function will return None.
The return statement is used for two things.
• Return a value to the caller
• To end and exit a function and go back to its caller

RETURNING MULTIPLE VALUES:

1)Using Tuple: A Tuple is a comma separated sequence of items. It is created with orwithout (). Tuples are
immutable.
def fun():
str = "geeksforgeeks"

(
x = 20
return (str, x)
y = fun()
print(y)

2. Using a list: A list is like an array of items created using square brackets. Theyare different from arrays
as they can contain items of different types. Lists are different from tuples as they are mutable.

def fun():

str = "geeksforgeeks"

x = 20
Example:
return [str, x];
['geeksforgeeks', 20]
list = fun()

print(list)

3. Using a Dictionary: A Dictionary is similar to hash or map in other languages.

def fun():

d = dict();

d['str'] = "GeeksforGeeks"

d['x'] = 20 Example:

return d {'x': 20, 'str': 'GeeksforGeeks'}

# Driver code to test above


method

d = fun()

print(d)
3.8 VARIABLE SCOPE:

 A variable which is defined within a function is local to that function.


 A local variable can be accessed from the point of its definition until the end of the function in
which it is defined. It exists as long as the functionis executing.
 Function parameters behave like local variables in the function. Moreover, whenever we use the
assignment operator (=) inside afunction, a new local variable is created.
 Global variables are those variables which are defined in the main bodyof the program file.
 They are visible throughout the program file. As a good programming habit, you must try to
avoid the use of global variables because they mayget altered by mistake and then result in
erroneous output.

USING THE GLOBAL STATEMENT:


To define a variable defined inside a function as global, you must use the globalstatement. This declares
the local or the inner variable of the function to have module scope.
RESOLUTION OF NAMES:
Scope defines the visibility of a name within a block. If a local variable is defined in a block, its scope is
that particular block.
If it is defined in a function, then its scope is all blocks within thatfunction.
When a variable name is used in a code block, it is resolved using thenearest enclosing scope.
If no variable of that name is found, then a NameError is raised.
In the code given below, str is a global string because it has been definedbefore calling the function.

3.9 RECURSIVE FUNCTIONS:


A recursive function is defined as a function that calls itself to solve a smaller version of its task until a
final call is made which does not require a call to itself. Every recursive solution has two major cases,
which are as follows:
• base case, in which the problem is simple enough to be solved directly withoutmaking any further
calls to the same function.
• recursive case, in which first the problem at hand is divided into simpler subparts.

The steps used in recursive programs:


`
Step 1: Specify the base case which will stop the function from making a call toitself.
Step 2: Check to see whether the current value being processed matches withthe value of the base case.
Step 3: Divide the problems into smaller or simpler sub-problems
Step 4: Call the function on the sub-problem
Step 5: Combine the results of the sub-problemsStep 6: Return the result of the entire problem.
TOWER OF HANOI
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks.The objective of the
puzzle is to move the entire stack to another rod, obeying the following rules:
1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk from one of the stacks andplacing it on top of another
stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.
Note: Transferring the top n-1 disks from source rod to Auxiliary rod can againbe thought of as a fresh
problem and can be solved in the same manner.

Step1:Start the program


Step2:Procedure HANOI(disk,source, destination,auxilary)
Step3:IF n==1,
Step3.1:Move disk from source to destination
Step4:ELSE
Step4.1:HANOI(n-1,source,auxilary,dest)
Step4.2:MOVE disk from source to destination
Step4.3:HANOI(n-1 auxilary, destination,source)
ALGORITHM:

Step5:END-IF
Step1:Start the program
Step6:Stop
Step2:Procedure TowerOfHanoi (disk,source, destination,auxilary)
Step3:IF n==1,
Step3.1:Move disk from source to destination
Step4:ELSE
Step4.1:TowerOfHanoi (n-1,source,auxilary,dest)
Step4.2:Move disk from source to destination
Step4.3:TowerOfHanoi (n-1 auxilary, destination,source)
Step5:END-IF
Step6:Stop

`
PROGRAM:

1. # Creating a recursive function


2. def
deftower_of_hanoi(disks, source, auxiliary,
TowerOfHanoi(n , source, target):
destination, auxiliary):
3. if(disks == 1):
4.
ifprint('Move
n==1: disk 1 from rod {} to rod {}.'.format(source, target))
5. return
print "Move disk 1 from source",source,"to destination",destination
6. # function call itself
return
7. tower_of_hanoi(disks - 1, source, target, auxiliary)
8. TowerOfHanoi(n-1,
print('Move disk {} fromsource,
rod {} toauxiliary, destination)source, target))
rod {}.'.format(disks,
9. tower_of_hanoi(disks - 1, auxiliary,
print "Move disk",n,"from source, target) destination",destination
source",source,"to
10.
TowerOfHanoi(n-1, auxiliary, destination, source)
11.
12. disks = int(input('Enter the number of disks: '))
13. # #We are referring
Driver code source as A, auxiliary as B, and target as C
14. tower_of_hanoi(disks, 'A', 'B', 'C') # Calling the function
n=4
TowerOfHanoi(n,'A','B','C')
Output:# A, C, B are the name of rods
Enter the number of disks: 3
Move disk 1 from rod A to rod C.
Move disk 2 from rod A to rod B.
Move disk 1 from rod C to rod B.
Move disk 3 from rod A to rod C.
Move disk 1 from rod B to rod A.
Move disk 2 from rod B to rod C.
Move disk 1 from rod A to rod C.

LAMBDA FUNCTIONS OR ANONYMOUS FUNCTIONS:


Lambda or anonymous functions are so called because they are not declared as other functions using the
def keyword. Rather, they are created using the lambda keyword. Lambda functions are throw-away
functions, i.e. they are justneeded where they have been created and can be used anywhere a function is
required. The lambda feature was added to Python due to the demand from LISP programmers.
Lambda functions contain only a single line. Its syntax can be given as,

`
3.10 STRINGS:
 String is a sequence which is made up of one or more UNICODE characters.
 The character can be a letter, digit, whitespace or any other symbol.
 Python has a built-in string class named "str" that has many usefulfeatures.
 A string can be created by enclosing one or more characters in single, double or triple
quote.
 To declare and define a string by creating a variable of string type:
>>> name = "India"
>>> graduate = 'N’
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!'''
>>>country = name nationality = str("Indian")
Accessing Characters in a String - Index
 Individual characters in a string are accessed using the subscript ([ ])operator. The
expression in brackets is called an index.
 The index specifies a member of an ordered set and in this case it specifies the character
to be accessed from the given set of characters inthe string.

>>> str = "Hello World!"


>>> str[3]
>>> l

 The index of the first character is 0 and that of the last character is n-1where n is the
length of the string.
 The index must be an integer (positive, zero or negative).
 Negative indices are used when the characters of the string are accessedfrom right to left.
 Starting from right hand side, the first character has the index as -1 andthe last character
has the index –n where n is the length of the string.
>>> str[-3]
>>> r
 The index can also be an expression including variables and operators butthe expression
must evaluate to an integer.

>>> str = "Hello World!"


>>> str[2+4]
>>> W
 If index bound exceeded (below 0 or above n-1), then an IndexError israised.
String slices:

 A substring of a string is called a slice. The slice operation is used torefer to sub-parts of
sequences and strings within the objects.
 Slicing operator [ ] is used to access subset of string from original string
 Syntax :
`
string_var [START INDEX : END INDEX: STEP]

Ex. str[n : m : k] returns every kth character extracted fromthe string starting from
index n (inclusive) and ending at m (exclusive).
By default, the step size is one

>>> str1= "Hello World!"


>>> str1[7:10]
>>> 'orl'
>>> str1[0:10:2]
>>>'HloWr'
>>> str1[0:10:3]
>>>'HlWl'

Note :
1. The numbers of characters in the substring will always be equal tom-n
>>> str1= "Hello World!"
#index that is too big is truncated down to#the end of the string
>>> str1[3:20]
>>> 'lo World!'

2. If the first index is not mentioned, the slice starts from index 0.
>>> str1[:5]
>>> 'Hello'
3. If the second index is not mentioned, the slicing is done till thelength of the string.
>>> str1[6:]
>>>'World!'
4. Negative indexes can also be used for slicing.
>>> str1[-6:-1]
>>> 'World'

Traversing a String:
To access each character of a string or traverse a string, for loop and whileloop are used
(A) String Traversal Using for Loop:
>>> str1 = 'Hello World!'
>>> for ch in str1:
print(ch,end = '')
>>> Hello World! #output of for loop
 for loop starts from the first character of the string str1 andautomatically ends when the
last character is accessed.

(B) String Traversal Using while Loop:


>>> str1 = 'Hello World!'
>>> index = 0
>>> while index < len(str1):
print(str1[index],end = '')index += 1
>>> Hello World! #output of while loop
 while loop runs till the condition index< len(str) is True, where indexvaries from 0 to
len(str1) -1.
Immutability:
 A string is an immutable data type.
`
 The contents of the string cannot be changed in-place after it has been created. An
attempt to do this would lead to an error.
>>> str1 = "Hello World!"
#if we try to replace character 'e' with 'a'
>>> str1[1] = 'a'
TypeError: 'str' object does not support itemassignment

3.11 String Operations and Functions:


i. Concatenation : Python allows to join two strings using concatenation operator
plus which is denoted by symbol +.
>>> str1 = 'Hello' #First string
>>> str2 = 'World!' #Second string
>>> str1 + str2 #Concatenated strings
>>> 'HelloWorld!'
ii. Repetition: Python allows to repeat the given string usingrepetition operator which
is denoted by symbol *.
#assign string 'Hello' to str1
>>> str1 = 'Hello'
#repeat the value of str1 2 times
>>> str1 * 2
>>>'HelloHello'

iii. Membership : Python has two membership operators 'in' and 'notin'. The 'in'
operator takes two strings and returns True if the firststring appears as a substring
in the second string, otherwise it returns False.
>>> str1 = 'Hello World!'
>>> 'W' in str1
>>> True
>>> 'My' in str1
>>> False
The 'not in' operator also takes two strings and returns True if thefirst string does
not appear as a substring in the second string, otherwise returns False.
>>> str1 = 'Hello World!'
>>> 'My' not in str1
>>> True
>>> 'Hello' not in str1
>>> False
iv. Comparing strings: Two strings can be compared using relationaloperators which
return True or False

`
v. len():This function returns the length of the string.Ex:>>>t=”Welcome”
>>> len(t)
7
vi. max( ) : This function returns the maximum alphabetical characterfrom the string
vii. min( ) : This function returns the minimum alphabetical characterfrom the string
Ex: >>> max(t)
'o'
>>> min(t)
'e'
viii. ord( ) : This function returns the ASCII code of thecharacter

ix. chr( ) : This function returns character represented by a ASCIInumber.

x. sorted():This function returns sorted string as list .


Ex: >>> sorted(t)
['e', 'h', 'l', 'l', 'o']
3.12 String Methods:

1. str.lower ( ) : Return a string with all the cased characters converted tolowercase.
>>> str="THIS IS STRING EXAMPLE. . . .WOW ! ! ! "
>>> str.lower ( )
' this is string example. . . .wow ! ! ! '

2. str.upper ( ): Return a string with all the cased characters converted touppercase.
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.upper ( )
' THIS IS STRING EXAMPLE. . . . WOW ! ! ! '

3. str.istitle ( ) : Return True, if the string is title cased, otherwise False isreturned.
>>> str=" This Is String Example. . .Wow ! ! ! "
>>> str . istitle ( )
True

4. str.capitalize ( ) : Return a string with its first character capitalized andthe rest lowercase.
`
>>> str=" this Is stRing example ....... wow ! ! ! "
>>> str.capitalize ( )
' This is string example ...... wow ! ! !

5. str.title ( ) : Return a title cased version of the string, where words startwith an uppercase
character and the remaining characters are lowercase.
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.title ( )
' This Is String Example. . . .wow ! !

6. str.swapcase ( ) : Return a copy of the string with reversed charactercase.


>>> str='' This is string example. . . .WOW ! ! ! "
>>> str . swapcase ( )
' tHIS IS STRING EXAMPLE. . . .wow ! ! ! '

7. str.isalnum( ) : Return true if all characters in the string arealphanumeric, false otherwise.

>>> str=" this2009 ”


>>> str.isalnum ( )
True
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.isalnum( )
False

8. str. isalpha ( ) : Return true if all characters in the string arealphabetic, false otherwise.

>>> str=" this "


>>> str.isalpha ( )
True
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.isalpha ( )
False

9. str.isdigit( ) : Return True, if all characters in the string are digits,otherwise False is
returned.
>>> str="this2009"
>>> str.isdigit ( )
False
>>> str=" 2009 "
>>> str.isdigit ( )
True

10. str . isspace ( ) : Return True, if there are only whitespace characters inthe string,
otherwise False is returned.
>>> str= " "
>>> str.isspace ( )
True
>>> str=" This is string example. . . .wow ! ! ! "
>>> str.isspace ( )
False

11. str.islower ( ) : Return True, if all cased characters in the string are inlowercase, false
`
otherwise.
>>> str=" THIS is string example. . . .wow! ! ! "
>>> str.islower( )
False
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.islower ( )
True

12. str.isupper ( ) : Return True, if all cased characters in the string areuppercase, otherwise
False is returned.

>>> str="THIS IS STRING EXAMPLE. . . .WOW ! ! ! "


>>> str.isupper ( )True
>>> str=" THIS is string example. . . .wow ! ! ! "
>>> str.isupper ( )False

13. str.count(sub[,start[, end]]) : Return the number of non-overlappingoccurrences of sub-


string sub in the range [start, end]. Optional arguments start and end are interpreted as in
slice notation.
>>> str=" this is string example. . . .wow ! ! ! "
>>> sub=" i "
>>> str.count (sub , 4 , 40)
2

14. str.find(sub[,start[,end]]) : Return the lowest index in the string where the sub-string sub
is found, such that sub is contained in the slice s [ start:end]. Optional arguments start and
end are interpreted as in slice notation.Return -1, if the sub is not found.
>>> str1=" this is string example. . . .wow ! ! ! "
>>> str2=" exam "
>>> str1.find ( str2 )
15
>>> str1.find ( str2 , 10 )
15

15. str.index ( sub [ , start [ , end ] ] ) : Return the lowest index in the stringwhere the sub-
string sub is found, such that sub is contained in the slice s[ start: end] (like find ( ) but
raise ValueError when the sub-string is not found)
>>> str1=" this is string example. . . .wow ! ! ! "
>>> str2=" exam "
>.> str1. index ( str2 )
15
>>> str1.index ( str2 , 10 )
15

16. str.rfind(sub[,start[, end]] ) : Return the highest index in the string where the sub-string
sub is found, such that sub is contained within s [start: end]. Optional arguments start and
end are interpreted as in slicenotation. Return -1 on failure.

`
>>> str1=" this is really a string example. . . .wow !
! ! "
>>> str2=" is "
>>> strl.rfind ( str2 )
5
>>> str1.rfind ( str2 , 0 , 10 )
5
17. str. join ( iterable ) : Return a string which is the concatenation of the
strings in the iterable. The separator between elements is the string str providing this
method.
>>> str="-"
>>> seq= ( " a " , " b " , " c " )
>>> str. join ( seq )
' a-b-c '
>>> seq=[ " a " , " b " , " c " ]
>>> str.join (seq)
' a-b-c '

18. str.replace ( old , new [ , count ] ) : Return a string with all occurrences of substring old
replaced by new. If the optional argument count is given, only the first count occurrences
are replaced.
>>> str=" this is string example. . . . wow ! ! ! this
is really string"
>>> str.replace (" is "," was ")
'thwas was string example. . . .wow ! ! ! thwas was
really string’

19. str.center ( width [ , fillchar ] ) : Return centered string of length width. Padding is done
using optional argument fillchar (default is a space).
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.center ( 40 ,' a ' )
' aaaathis is string example. . . .wow ! ! ! aaaa'

20. str.ljust ( width [ , fillchar ] ) : Return the string left-justified in a stringof length width.
Padding is done using the optional argument fillchar (default is a space). The original
string is returned if the width is less thanor equal to len(str).
>>> str="this is string example. . . .wow! ! ! "
>>> str . ljust (50, ' 0 ' )
'this is string example. . . .wow ! !
!000000000000000000 '

21. str.rjust ( width [ ,fillchar ] ) : Return the right-justified string of lengthwidth. Padding is
done using the optional argument fillchar (default is a space). The original string is
returned if the width is less than or equal to len(str).
>>> str="this is string example. . . .wow ! ! ! "
>>> str.rjust ( 50 , ' 0 ' )
'000000000000000000this is string example. . . .wow ! !
! '

22. str.strip ( [ chars ] ) : Return a string with the leading and trailing characters removed.
The chars argument is a string specifying the set of characters to be removed. If omitted or
None, the chars argument defaultsto removing whitespace.

`
>>> str=" 0000000this is string example. . . . wow ! ! ! 0000000 "
>>> str.strip ( ' 0 ' )
'this is string example. . . .wow ! ! ! '

23. str.split ( [ sep [ , maxsplit ] ] ) : Return a list of the words from the string using sep as
the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will
have at most maxsplit + 1 elements). If maxsplit is not specified or -1, then all possible
splits are made. If sep is not specified or None, any whitespace string is a separator.

>>> str="Line1-abcdef \nLine2-abc \nLine4-abcd"


>>> str . split ( )
['Line1-abcdef', ' Line2-abc ', ' Line4-abcd ' ]

24. str. splitlines ( [ keepends ] ) : Return a list of the lines in the string, breaking at line
boundaries. Line breaks are not included in the resultinglist unless keeping is given.

>>> str="1ine1-a b c d e f\n1ine2- a b c\ n\n1ine4- a b c d "


>>> str.splitlines ( )
[ ' Line1-a b c d e f', ' Line2- a b c ' , ' ' , ' Line4- a b
c d ' ]

Programs

Write a Python program to find String palindrome

a=input("Enter a string:")b=a.lower()
c=b[::-1]
if b==c:
print(a,"is a palindrome")else:
print(a,"is not a palindrome")

Output:
Enter a string: RadarRadar is a palindrome

Write a Python program to perform linear search using list

def linear(lst,sval):
for i in range(len(lst)):
if lst[i]==sval:
return(i)
return -1

n=int(input("Enter no. of elements:"))l=[]


for i in range(n):
val=int(input("enter value:"))
l.append(val)
print(l)
searchval= int(input("enter value to be searched:"))
a=linear(l,searchval)
if a==-1:
print("Element not found")
else:
print("Element found at index",a)
`
Output:
Enter no. of elements:5
enter value:23
enter value:45
enter value:67
enter value:89
enter value:100
[23,45,67,89,100]
enter value to be searched:67
Element foundat index 2

Write a Python program to perform binary search using list


Program:
def binsearch(lst,sval):
low,high=0,(len(lst)-1)
while (low<high):
mid=(low+high)//2
if lst[mid]<sval:
low=mid+1
elif lst[mid]>sval:
high=mid-1
else:
return(mid)
return -1
n=int(input("Enter the no of elements in list:"))l =[]
for i in range(n):
ele=int(input("Enter the list elements:"))
l.append(ele)
x = int(input("Enter the element to search:"))
a=binsearch(l,x)
if a==-1:
print("Element not found")
else:
print("Element found at index",a)
Output:
Enter the no of elements in list:5
Enter the list elements:2
Enter the list elements:3
Enter the list elements:4
Enter the list elements:5
Enter the list elements:6
Enter the element to search:8
Element not found
5. Write a function called is_anagram that takes two strings and returns True if they are
anagrams.

`
def
is_anagram(s1
,s2):
s1=sorted(s1)
s2=sorted(s2)
if(s1==s2):
return
Trueelse:
return False

a=input("enter 1st string:")


b=input("enter 2nd string:")
print("Is Anagram:",is_anagram(a.lower(),b.lower()))

Output:
enter 1st string:Ajax
enter 2nd string:Jaxa

Is Anagram: True

Write a function deleteChar() which takes two parameters one is a string and other is a
character. The function should create a new string after deleting all occurrences of the
characterfrom the string and return the new string.
Program:
def delchar(string,char):
str=" "
for i in string:
if i==char:
str=string.replace(i, '')
return str
a=input("enter string:")
b=input("enter char to be deleted:")
print("the string:", delchar(a, b))

Output :
enter string:abcdxyzd
enter char to be deleted:d
the string: abcxyz

Write a Python program to count Uppercase, Lowercase, special character and numeric
values in a given string.

Programs:

`
v='Shop open@3pm'
s=v.replace(" ","")
a=0
b=0
c=0
d=0
for i in s:
if i.isdigit()==True:
a+=1
elif i.isupper()==True:
b+=1
elif i.islower()==True:
c+=1
else:
d+=1
print('digit values:',a)
print('uppercase letters:',b)
print('lower case letters:',c)
print('special char:',d)

Output:
digit values: 1

`
uppercase letters: 1
lower case letters: 9
special charc: 1

6. Count no. of vowels and consonants in stringProgram:


str=input("Enter string:")

str1="".join(str.split())vowel="aeiou"
vcount=0ccount=0

for i in str1:
if i.lower() in vowel:vcount+=1
else:
ccount+=1
print("No. of vowels in string ",str ,vcount) print("No. of consonents in string ",str
,ccount)

Output
Enter string:python program
No. of vowels in string python program 3
No. of consonents in string 11

You might also like