Flow of control & String
Data Type
Objectives
In this session, you will learn to:
Update variable values.
Use looping constructs.
Define strings.
Implement predefined methods in string.
Implement format operator.
Updating Variable
Value
To update value in a variable, it must be first declared with
a value.
Code Throws error, because the value of “x” is not
declared in the program.
Updating Variable
Value(Contd.)
Code works fine, since the value is declared
before the updation of the variable
While Statement
While Loop is used to execute a set of instructions for a
specified number of times until the condition becomes False.
1. Working of While Loop
• Evaluate the condition,
yielding True or False.
• If the condition is false,
exit the while statement
and continue execution at
the next statement.
• If the condition is true,
execute the body and
then go back to step 1.
While Statement (Contd.)
Syntax:
While Condition:
statements;
Applying
syntax to
program
Just a Minute
Predict the output of the following code:
n=2
while n >= 10:
if n%2==0:
print n
n = n+1
Just a Minute
Predict the output of the following code:
n=2
while n >= 10:
if n%2==0:
print n
n = n+1
Answer: 2,4,6,8,10
Infinite Loops
Sequence of instructions in a computer program which
loops endlessly.
Known as an endless loop or unproductive loop.
Reasons:
. • Loop having no terminating
condition.
• Having Condition that can never
be satisfied
• Condition that causes the loop to
start over.
Infinite Loops (Contd.)
Example: -1
-2
>>> var1=-1 -3
>>> while var1<0: -4
print(var1) -5
var1=var1-1 -6
-7 Condition will be always true, since
Output -8 the value of var1 is decrementing
-9 every time
-10
-11
-12
-13
.
.
.
Infinite Loops (Contd.)
Solution to an infinite loop
Use break Statement.
The break statement is used to exit from the loop.
The break statement prevents the execution of the remaining loop.
while True: Output:
line = raw_input('> ') >hello there
if line == 'done': hello there
Output
break > finished
print line finished
print 'Done!' > done
Done!
Finishing Iterations with
Continue
Continue Statement
Used to skip all the subsequent instructions and take the control back
to the loop.
while True:Sub-bullet1
line = raw_input('> ')
Sub-bullet2 > hello there
if line[0] == '#' : hello there
continue Output > # don't print this
if line == 'done': > print this!
break print this!
print line > done
print 'Done!' Done!
Just a Minute
The __________statement is used to exit from
the loop and ________ statement is used to skip
instructions and take control to the beginning of
the loop.
Just a Minute
The __________statement is used to exit from
the loop and ________ statement is used to skip
instructions and take control to the beginning of
the loop.
Answer: break and continue
Definite Loops Using “for”
Used to execute a block of statements for a specific number
of times.
Used to construct a definite loop.
Syntax: for <destination> in <source>
statements
print <destination>
Definite Loops Using “for”
(Contd.)
Example :
Output
Happy New Year: Joseph
Happy New Year: Glenn
friends = ['Joseph', 'Glenn', 'Sally'] Happy New Year: Sally
for friend in friends: Done!
print 'Happy New Year:', friend
print 'Done!'
Loop Patterns
Loops are generally used
To iterate a list of items.
To view content of a file.
To find the largest and smallest data.
These Loops are Constructed by:
1.Initializing one or more variables
2.Performing some computation on each
item in the loop body
3.Looking at the resulting variables when
the loop completes
Counting and Summing
Loops
Example : To find the number of items in a list, the following loop is
to be used.
total = 0 Output : 154
for itervar in [3, 41, 12, 9, 74, 15]:
total = total + itervar
print 'Total: ', total
Maximum and Minimum
Loops
Example : To find min and max of the given numbers in the list.
smallest = None largest = None
for itervar in [3, 41, 12, 9, 74, 15]: for itervar in [3, 41, 12, 9, 74, 15]:
if smallest is None or itervar < smallest: if largest is None or itervar > largest :
smallest = itervar largest = itervar
print 'Smallest:', smallest print 'Largest:', largest
Output
3
3 41
72
Activity
Activity : Implementing Loop
Problem Statement:
Write a program which repeatedly reads numbers until the user enters “done”. Once “done”
is entered, print out the total, count, and average of the numbers. If the user enters anything
other than a number, detect their mistake using try and except and print an error message
and skip to the next number.
For Example, executing the program will look as follows:
Enter a number: 4
Enter a number: 5
Enter a number: bad data
Invalid input
Enter a number: 7
Enter a number: done
16 3 5.33333333333
Hint: Use while loop to accept values from user until the user enters “done”.
Define String
A string is a sequence of characters .
Single quotes or double quotes are used to represent strings.
Example : A Simple String representation
Accessing a String
String Representation in memory:
Address/Index
To access the a character from a particular string in the following
way.
>>> stdname='Gagan'
>>> letter=stdname[2] Output
>>> print(letter)
g
Special String Operators
Table : Special Operators used in String
Example[ Assume
Operator Description
a=“Hello”, b=“Python”]
a + b will give
+ Concatenation - Adds values on either side of the operator
HelloPython
Repetition - Creates new strings, concatenating multiple
* a*2 will give -HelloHello
copies of the same string
[] Slice - Gives the character from the given index a[1] will give e
[:] Range Slice - Gives the characters from the given range a[1:4] will give ell
Membership - Returns true if a character exists in the
in H in a will give 1
given string
Membership - Returns true if a character does not exist in
not in M not in a will give 1
the given string
Traversing a String
Starts at the Selects each Continue iteration
Compute Logic
beginning character in turn till end of string
Example :
Output
G
>>> index=0
e
>>> stdname='George'
>>> while index<len(stdname): o
letter=stdname[index] r
print(letter) g
index=index+1 e
Just a Minute
In Python, Strings starts with Index ____________.
Just a Minute
In Python, Strings starts with Index ____________.
Answer: Zero
Built-in String Methods
Table : Built in String Methods
SL NO METHOD NAME DESCRIPTION
1 Capitalizes first letter of string
capitalize()
Returns true if string has at least one cased character and all
2
isupper() cased characters are in uppercase and false otherwise.
3 Returns true if string is properly "titlecased" and false otherwise.
istitle()
4 Returns the length of the string
len(string)
5 Converts all uppercase letters in string to lowercase.
lower()
6 Removes all leading whitespace in string.
lstrip()
7 Converts lowercase letters in string to uppercase.
upper()
Splits string according to delimiter str (space if not provided) and
8 split(str="", returns list of substrings; split into at most num substrings if
num=string.count(str)) given.
String Comparison
Strings can be compared using == operator.
CASE
>>> (I)
fruit1="Apple" CASE(II) >>> fruit1="Apple"
>>> fruit2="Apple" >>> fruit2="Mango"
>>> if fruit1==fruit2: >>> if fruit1!=fruit2:
print("Both are equal") print("Both are not equal")
Output
Both are equal Both are not equal
Format Operator
“%” operator allows to construct strings , replacing parts of
the strings with the data stored in variables.
“%” operator will work as modulus operator for strings.
“%” operator works as a format operator if the operand is
string.
Example
>>> fruits=20
>>> 'There are %d fruits in the basket ' %fruits
'There are 20 fruits in the basket '
Activity
Activity : Manipulating String
Problem Statement:
Write a program to prompt any statement with punctuation characters, print the statement
after removing all the punctuation characters in lower case by separating individual words.
Hint: Use translate() and lower().
Activity
Activity : Slicing the String
Problem Statement:
Write a program to accept the following Python code that stores a string:
str = 'X-DSPAM-Confidence: 0.8475'
Use find and string slicing to extract the portion of the string after the colon character and
then use the float function to convert the extracted string into a floating point number.
Hint: Use split() and float().
Prerequisite: For this activity please refer “mbox-short.txt” available in
“Data_File_For_Students” folder.
Summary
In this session you have learned to:
Update variable values.
Use looping constructs.
Define strings.
Implement predefined methods in string.
Implement format operator.