How to use break statement to exit a loop

break out of a loop

The break statement exit a loop statement. We can use break statement with while or for loop.

When you've found a square, simply break out of the loop:


from math import sqrt 
for n in range(99, 0, -1): 
    root = sqrt(n) # from  w ww.  j ava 2  s.  c  o  m
    if root == int(root): 
        print n 
        break 

The code above generates the following result.

break out of a while loop


while True: # from  w w w .  j a va2  s.c  o m
    word = raw_input('Please enter a word: ')
    if not word: break 
    print 'The word was ' + word
 

The code above generates the following result.

Use break to stop execution and break out of the current loop Use continue to stop execution of the current iteration and start the next iteration of the current loop


word = "this is a test from java2s.com"
string = ""#  w ww. j  a va  2s .  com
for ch in word:
    if ch == 'i':
        string +='y'
        continue
    if ch == ' ':
        break
    string += ch
print string

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules