The while True and break statement

Execution of an infinite while loop can be broken by the use of the break statement. Let's understand with an example:

sum = 0
while True:
data = int(raw_input("Enter the data or press 0 to quit :"))
if data == 0:
break
sum = sum+data
print "Sum is ", sum

Here we intend to print the sum of numbers being entered. In the preceding example, the while loop condition has been set to be Boolean, that is, True. In this case, the while loop will continue to execute infinitely as the condition will always be true. However, we can break this loop by setting up a condition check inside the while loop and then using a break statement. So, the loop will continue to run until the user keeps on entering numbers, but it will terminate as soon as the number 0 is entered. Here, once 0 is entered, the if condition inside the while loop will check and as the number entered is 0, the code inside the if block will execute, which is a break statement. This will terminate the loop and print the sum of the numbers entered as shown here:

Here, the while loop has Boolean value True, which is an entry condition for the while loop. In this case, the loop would execute at least once. But there is another way to achieve the preceding outcome without using the break statement. Let's have look at another example:

sum = 0
flag = 1
while flag == 1:
data = int(raw_input("Enter the number or press 0 to quit :"))
if data == 0:
flag =0
sum = sum+data
print "Sum is ", sum

We have achieved the same output without using the break statement. Here, we have used a flag variable instead of a break statement:

The initial entry point of the while loop is the value of the flag variable as 1. Until the flag variable is 0, the loop will continue to execute. When 0 is entered, the value of flag variable becomes 0 and the loop terminates.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.69.199