Python Data Persistence – Repetition Control

Python Data Persistence – Repetition Control

A looping construct is normally designed to make a certain number of repetitions. For example, the Boolean expression in a while statement decides how many times the block will be repeatedly executed. In the case of for loop, it is decided by the length of iterable.
But what if a situation requires early termination of the loop? Consider an example: your program gives the user 10 chances to guess a secret number. Obviously, user input and comparison logic form the body of the loop. However, if the user guesses it right earlier than stipulated chances, naturally the loop should terminate without undergoing all repetitions. Following figure 2.14 explains this scenario:

Python Data Presistence - Repetition Control chapter 2 img 1

Python’s break keyword serves exactly this purpose. This keyword appears in a conditional statement inside the loop’s body. If and when the statement evaluates to true, the break statement causes the current loop to be abandoned before the stipulated number of repetitions.
Following Python code implements figure 2.14 flowchart algorithm. To start with a random integer is set as a secret number. (The randint ( ) function is defined in a built-in random module. More about it in the next chapter.) The while loop gives 10 chances for the user to guess it correctly but terminates early if the user gets it right.

Example

#secret-number.py
import random
secret=random.randint(1,10)
chances=0
while chances<10:
guess = int(input(1 enter your guess..'))
if guess==secret:
print ('you got that right!')
break
print ('try again..')chances=chances+1
if chances==10:
print ('chances exhausted, secret number is : 1,secret)

The output of the above code is shown below. However, your result is likely to be different because a secret number is generated randomly.

Output

E:\python37>python secret-number.py 
enter your guess . . 1 try again . . 
enter your guess . . 2 try again . . 
enter your guess . . 3 try again . . 
enter your guess . . 4 you got that right!

Python also has to continue the keyword which is more or less opposite to break. Instead of breaking out of the current loop, when encountered, continue sends program control back to the beginning of the loop. The remaining statements in the current iteration will not be executed.
A typical scenario of continuing in a loop is like this:
A loop accepts five numbers from the user and displays the sum. However, if a negative number is input, the user is forced to input again. The negative number is kept away from the sum operation. Look at the following flowchart (figure 2.16):

Python Data Presistence - Repetition Control chapter 2 img 2
Following Python code implements the above algorithm (figure 2.16).

Example

#continue-example.py
count=1
sum=0
while count<=5:
num=int ( input ( ' enter a number . . ' ) )
if num< 0:
print ('negative number is not accepted. Try again..')
continue
sum=sum+num
count=count+1
print ('sum=',sum)

Output:

E:\python3 7>python continue-example.py 
enter a number . . 2 
enter a number . . 4 
enter a number . . -1 
negative number is not accepted. Try again . .

enter a number . . 6 
enter a number . . -9 
negative number is not accepted. Try again . .

enter a number . . 3 
enter a number . . 1 
sum= 16

E:\python37>

else Statement with Loop

This might be a bit of a surprise to you if you know any C family language (e.g. C, C++, Java, C#, and so on.) The else keyword is normally used to describe the action to be taken when the expression in the if statement is false. While this usage is also defined in Python, else is also used along with looping constructs, both while and for.
When constructing a loop, you can use an optional else block just after the loop’s body. The rest of the statements follow after the else block. The else block comes into play after the loop is over, but before leaving the loop.

Example

#else with loop
while expression==True:
#while block
. .
#end of while block
else:
#else block
. .
#end of else block
#ret of the statements
. .

Following code is typical to use case of else with a loop. The objective is to determine whether the input number is prime or not. The number is successively divided by all numbers between 2 and n. If any number is able to divide it without leaving a remainder, it is a prime. After completion of the loop, else block displays a message of a prime number.

Example

#else-in-loop.py
num=int ( input ( " enter a number . . " ) )
x=2
while x<num:
if num%x==0:
print ("{ } is not prime.".format(num))
break
x=x+1
else:
print ("{ } is prime.".format(num))
print ('end of program')

Note that the else block won’t come into the picture if the loop breaks prematurely as it would happen in case the number is not prime. Here is the output of the above script:

Output:

E : \python37 'python else - in- loop . py 
enter a number . . 31 
31 is prime. end of program 

E:\python37 >python else-in-loop.py 
enter a number . . 24 
24 is not prime. end of program 

E:\python3 7.

It is possible to provide else block for the loop also. You can try writing the above prime number example using for loop.
Hint: You may have to use the range ( ) function in it.