Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views13 pages

04 Iterative Control Statements

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

04 Iterative Control Statements

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

ITERATIVE CONTROL STATEMENTS

Python provides a built-in range function that can be used for generating a sequence of
integers
The range() function can be represented in three different ways.
range(stop)
range() with one argument, generates series of numbers that starts at 0 and includes every
whole number up to, but not including, the number that was provided as the stop.
Example:
r = range ( 10 ) # 0…9
r = range ( 100 ) # 0…99
range(start, stop)
range() with two arguments, sets where it should start and where the series of numbers
should stop
Example:
r = range ( 1,10 ) # 1…9
r = range ( 1, 11 ) # 1..10
range(start, stop, step)
range() with three arguments, it sets where the series of numbers to start and stop , also
how big the difference will be between one number and the next. By default step value is 1
Example:
r = range ( 1 , 21 ,1 ) # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
r = range ( 1 , 21 , 2 ) # 1 3 5 7 9 11 13 15 17 19
Decrementing With range()
If your step is negative, then range() generates a series of decreasing numbers.
r = range ( 20 , 1 , -5 ) # 20 15 10 5
Indexing and slicing :
r = range ( 10,21) # 10 11 12 13 14 15 16 17 18 19 20
r [ 0 ] #10
r [ -1 ] #20
t= r [ 1 : 5 ] # 11 12 13 14
r [ 1 ] = 1000 #error
Example:
r = range(10)
0 1 2 3 4 5 6 7 8 9 => sequence
0 1 2 3 4 5 6 7 8 9 => +ve index L -> R
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 => -ve index L <- R

r [ 0 : 5 ] => r [ 0 : 5 : 1 ] => range of index 0 to 4 => 0 1 2 3 4


output: 0 1 2 3 4 (sub sequence)
r [ 3 : 8 ] => r[3:8:1] => range of index 3 to 7 => 3 4 5 6 7
output: 3 4 5 6 7 (subsequence)
r [ - 7 : - 2 ] => r[-7:-2:1] => range of index => -7 to -3 => -7 -6 -5 -4 -3
output: 3 4 5 6 7 (subsequence)
r [ 1 : - 2 ] =>r[1:-2:1] => range of index => 1 to -3 =>1 to 7=> 1 2 3 4 5 6 7
output: 1 2 3 4 5 6 7 (subsequence)
r [ 1 : ] => r[1:10:1] => range of index => 1 to 9 => 1 2 3 4 5 6 7 8 9
output: 1 2 3 4 5 6 7 8 9 (subsequence)
r [ 5 : ] => r[5:10:1]=>range of index => 5 to 9 => 5 6 7 8 9
output: 5 6 7 8 9 (subsequence)
r [ : - 1 ]=> r[0:-1:1] => range of index => 0 to -2 => 0 to 8 => 0 1 2 3 4 5 6 7 8
output: 0 1 2 3 4 5 6 7 8 (subsequence)
r [ : ] => r[0:10:1] => range of index => 0 to 9 => 0 1 2 3 4 5 6 7 8 9
output : 0 1 2 3 4 5 6 7 8 9 (subsequence)
r [ : : ] => r[0:10:1] => range of index => 0 to 9 => 0 1 2 3 4 5 6 7 8 9
output : 0 1 2 3 4 5 6 7 8 9 (subsequence)
r[ : :-1] => r[-1:-11:-1] => range of index => -1 to -10 => -1 -2 -3 -4 -5 -6 -7 -8 -9 -10
output: 9 8 7 6 5 4 3 2 1 0 (reverse of given suquence)
r [ 2 : - 1 : 2 ] => range of index => 2 to -2 => 2 to 8 => 2 4 6 8
output: 2 4 6 8 ( subsequence)
r [ 2 : - 1 : - 1 ] => empty subsequence
r [ - 1 : 2 : - 1 ] => range of index => -1 to 3 => -1 to -7 => -1 -2 -3 -4 -5 -6 -7
output: 9 8 7 6 5 4 3 ( subsequence)

r [ - 2 : 1 : - 1 ] => range of index => -2 to 2 => -2 to -8 => -2 -3 -4 -5 -6 -7 -8


output: 8 7 6 5 4 3 2
r [ -2 : 1 : - 2 ] => range of index => -2 to 2=> -2 to -8 => -2 -4 -6 -8
output: 8 6 4 2 (subsequence)

The while statement


A while statement is an iterative control statement that repeatedly executes a set of
instructions based on a provided Boolean expression (condition) .
___________________________________________________________________________
______
while boolean_expression:
while_suite

As long as the Boolean_expression (condition) is true, the while_suite (statements) with in


the loop are (re) executed.
Once the Boolean_expression becomes false, the iteration terminates and control continues
with the first statement after the while loop.
Note that it is possible that the first time a loop is reached, the condition may be false, and
therefore the loop would never be executed.

#program to print first ‘n’ natural numbers


n = int ( input ( ‘ Enter the value of n : ‘ ) )
i=1 #initialization of loop counter variable
while i < = n :
print(i, end=’ ‘) #action
i = i + 1 #updation of loop control variable
Test Case

Enter the value of n : 5


1 2 3 4 5

#program to print first ‘n’ natural numbers in reverse order


n = int ( input ( ‘ Enter the value of n : ‘ ) )
i=n #initialization of loop counter variable
while i > =1 :
print(i, end=’ ‘) #action
i = i - 1 #updation of loop control variable

Test Cases

Enter the value of n : 5


5 4 3 2 1

#program to find sum of first ‘n’ natural numbers


n = int ( input ( ‘ Enter the value of n : ‘ ) )
i,sum=1,0
while i < = n :
sum = sum + i
i = i + 1 # i+=1
print(‘sum of the first ‘, n ,’ natural numbers is’, sum)
Test Case

Enter the value of n : 5


Sum of the first 5 natural numbers is 15

Executing a loop for unknown number of times


The while loop is the best choice if the problem to be programmed requires the test
expression to checked first before executing the statements and if the statements are to be
executed unknown number of times and the loop is to be exited when the specified
condition becomes false.
The while loop is a good choice for menu driven programs and input data validations .

#program to perform arithmetic operations using menu


option=True
while ( option ) :
print(“1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n5.Exit”)
ch=int(input(“Enter your choice:”) )
if ch >= 1 and ch <= 4 :
a=int(input(“Enter first number:”) )
b=int(input(“Enter first number:”) )
if ch ==1:
result = a + b
print(“sum=“,result)
elif ch == 2
result=a-b
print(“difference=“,result)
elif ch==3
result=a*b
print(“product=“,result)
elif ch==4:
result= a/ b
print(“division=“,result)
elif ch==5:
option=False
else:
print(“Invalid choice”)

Using while for input validations


The while loop is especially useful for validating the input. If an invalid value is entered , a
loop can require that the user re-enter it as many times as necessary

#input validation
valid_entry=False
while(not valid_entry):
n=int ( input ( ‘ enter a number in the range 1-100 ’ ) )
if n>=1 and n<=100:
valid_entry=True
else:
print (‘invalid entry’)

#A simple game application


from random import randrange
while True:
n=int(input(‘Enter a number:’))
k=randrange(1,100)
print(‘Now Computer’s turn’,k)
if n>K:
print(‘You have won the game’)
break
else:
print(‘you have lost the game’)

For loops
Python’s for statement provides a convenient means of iterating over
sequences(lists,tuples,strings),
A for statement is an iterative control statement that iterates once for each element in a
specified sequence of elements. Thus , for loops are used to construct definite loops.
____________________________________________________
for k in sequence:
for _suite

#program to print values of a specific list of integers


nums = [10 , 20 , 30 ,40 ,50 ,60 ]
for k in nums:
print(k)
Iterating through while loop

#program to print the values of a specific list of integers


nums = [10 , 20 , 30 ,40 ,50 ,60 ]
k=0
while k < len(nums):
print(nums[k])
k= k + 1

Nesting of loops
One loop with in another loop is called nesting of loops for example two loops can be nested
as follows

#program to illustrate nested for loops


for i in [ 1 , 2 ] : #outerloop i=1 i=2
for j in [1 , 2 , 3 ] : #inner loop j =1 j=2 j=3 j =1 j=2 j=3
print(‘ i = ‘ , i , ‘ j = ‘ , j )
Nesting of loops
The nesting may continue upto any desired level

#program to illustrate nested for loops


for i in [ 1 , 2 ] : #outerloop i =1
i=2
for j in [1 , 2 , 3 ] : #inner loop j=1 j=2 j= 3
for k in [ 1 , 2 ] : #inner most loop k=1 k=2 k=1 k=2 k=1 k=2
print(‘ i = ‘ , i , ‘ j = ‘ , j , ‘ k = ‘ , k )
Transfer statements
Statements that transfer control from one part of the program to another part of the
program
The break statement
The break statement terminates the loop containing it. Control of the program is transferred
to the statement immediately after the suite of the loop.

#program to illustrate the use of break


for i in range(1,11) : # 1 2 3 4 5 6 7 8 9 10
if i == 5 :
break
print(“\n%d”.%(i) )

OUTPUT

1
2
3
4

The continue statement


The continue statement causes to skip the rest of the suite inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.

#program to illustrate the use of continue


for i in range(1,11) : # 1 2 3 4 5 6 7 8 9 10
if i == 4:
continue
print(i)

When i is equal to 4 the continue statement causes the loop to skip the print statement and
begin the next iteration
The output of the loop is : 1 2 3 5 6 7 8 9 10

Nested loops , break

When loops are nested the break will only terminate the corresponding loop only
#program to illustrate break statement in nested loops
for i in [ 0 , 1 , 2 ] : # i=0 i=1 i=2
for j in [ 0 , 1 , 2 ] : # j=0 j=1 j=2
if i == j :
break
print(“\n%d….%d”.%(i,j))

OUTPUT

1…0
2…0
2…1

Nested loops , continue


When loops are nested the continue statement affects the corresponding loop only

#program to illustrate continue in nested loops


for i in [0,1,2]: # i=0 i=1 i=2
for j in [0,1,2]: # j=0 j=1 j=2 j=0 j=1 j=2 j=0 j=1 j=2
if i == j:
continue
print(“\n%d….%d”.%(i,j))

OUTPUT

0….1 1…0 2…0


0…2 1…2 2…1
#program to print odd numbers using continue
num = range(1,11) # 1 2 3 4 5 6 7 8 9 10
for i in num:
if i%2==0:
continue
print (i)

OUTPUT:
1
3
5
7
9

while..else
The complete general syntax of the while loop

while boolean_expression:
while_suite
else:
else_suite

The else clause is optional. As long as the boolean_expresssion is True , the while block’s
suite is executed. If the boolean_expression is or becomes False , the loop terminates and if
the optional else clause is present its suite is executed .Inside the while bolck’s suite , if a
continue statement is executed , control is immediately returned to the top of the loop , and
the boolean_expression is evaluated again .If the loop does not terminate normally , any
optional else clause ‘s suite is skipped .
If the loop is broken out or due to a break statement , or a return statement (if the loop is in
a function or method) , or if an exception is raised , the else clause’s suite is not executed.

for …in..else loop


The full syntax of the for ….in loop also includes an optional else clause

for expression in iterable :


for_suite
else:
else_suite

The expression is normally either a single variable or a sequence of variables, usually in the
form of tuple. If a tuple or list is used for the expression ,each item is unpacked into the
expression’s items.
If a continue statement is executed inside the for….in loop’s suite, control is immediately
passed to the top of the loop and the next iteration begins. If the loop runs to completion it
terminates, and any else is executed . if the loop is broken out due to a break statement , or
a return statement(if the loop is in a function or method), or if an exception is raised , the
else clause’s suite is not executed.

You might also like