Friday, 22 July 2016

Break keyword in python

break statement is used in python  to terminate the loop . Loops basically iterate a block of code untill condition is become false , but sometimes we want to terminate the current iteration or whole loop without checking the condition . The most common use of break statement is when some external condition is triggered and requiring a hasty exit from a loop . We can use the break keyword or statement in both loops that is while and for .

Syntax of break keyword in python:

break

>>> list1=[1,2,3,4,5,6,7,8]
>>> for a in list1:
...     if  a==6:
...         break
...     print a
...
1
2
3
4
5
>>>

Second example of break keyword with while loop: -

var1 =20
while var1> 0:
    print 'Current value :', var1
    var1=var1 -1
    if var1==8:
        break
print 'bye'

output would be 

Current value : 20
Current value : 19
Current value : 18
Current value : 17
Current value : 16
Current value : 15
Current value : 14
Current value : 13
Current value : 12
Current value : 11
Current value : 10
Current value : 9
bye
softcrayons tech solutions provide best job oriented training on python course.

No comments:

Post a Comment