python

Python Break and Continue

The Break Statement

Normally a while loop ends only when the test condition in the loop becomes false. ​
However , with the help of a break statement a while loop can be left prematurely ​

while test expression:
    body of while
    if condition:
        break
    body of while
    statement(s)

Now comes the crucial point: ​
If a loop is left by break then ​the else part is not executed.

Example:

    
i=1​

while i<=10:​

    if(i==5):​

        break​

    print(i)​

    i=i+1​

else:   ​

    print("bye")    
    

Output:


1
2
3
4    

Exercise:

You have to develop a number guessing game. The program will generate a random integer secretly. Now it will ask the user to guess that number . If the user guessed it correctly then the program prints “Congratulations! You guessed it right” . ​
If the number guessed by the user is larger than the secret number then program should print “Number too large” and , if the number guessed by the user is smaller than the secret number then program should print “Number too small” . ​
This should continue until the user guesses the number correctly or quits . If the user wants to quit in between he will have to type 0 or negative number

In Python , we have a module named random
.​ This module contains a function called randint() , which accepts 2 arguments and returns a random number between them.​

    
import random​

a=random.randint(1,20)​

print("Random number is",a)​       
    
Output:
Random number is 16

Solution:

    
import random​

secretno=random.randint(1,100)​

guess=secretno+1​

while guess!=secretno:​

    guess=int(input("Guess the secret number:"))​

    if(guess<=0):​

        print("So Sorry! That you are quitting!")​

        break;​

    elif(guess>secretno):​

        print("Your guess is too large. Try again!")​

    elif(guess"secretno):​

        print("Your guess is too small. Try again!")​

    else:​

        print("Congratulations! You guessed it right!")​
 

The Continue Statement

The continue statement in Python returns the control to the beginning of the while loop. ​
It rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.​

    
while test expression:
    #code inside while loop
    if condition:
        continue
    #code inside while loop
#code outside while loop

    

Example:


i=0​

while i<10:​

    i=i+1​

    if(i%2!=0):​

        continue​

    print(i)​
Output:
    
2
4
6
8
10