Infinite Loops and Break

Infinite loops can be stopped using break statement. In our next example the loop is obviously an infinite loop because the logical expression after a while statement is simply logical constant (Boolean value) True:
n = 100 
while True:
 print n 
 n = n – 1
print ‘Done’
If you run this code you’ll learn that this program will run forever until you stop it because the logical expression at the top of the loop is always true by virtue of the fact that the expression is the constant value True.
As you can see this is dysfunctional infinite loop but we can make this loop finite using if condtional statement and brake statement.
n = 10 
while True:
 print n 
 n = n – 1 
 if n == 0:
       break
print ‘Done’ 
10 
9 
8 
7 
6 
5
4
3
2
1
Done
Example – Suppose you want to take an input from the user until they type done. You could write something like:
while True: 
 line = raw_input (‘=> ‘)
 if line == ‘done’:
        break 
 print line 
print ‘Done!’

=> something
=>done 
Done!
Each time this code will prompt an arrow (equal sign + angle bracket). If the user type done, the break statement will be used and it will exit the loop. Then you’ll get string “Done!”. Using break statements in while loops is very useful because you can check the condition anywhere in the loop and you can express the stop condition affirmatively rather than negatively. 

1 komentar: