Chapter 2 Lab Exercise
4.4 Break, Continue, and Else
4.4 b
reaK, C
onTinue,
anDe
lseThe break statement is used to terminate a current loop and resume execution at the next statement. It can be used in both for
and while loops. Here is an example of its use inside a for loop:
The output of this would be:
Figure 4.13: List element printed up to element six as break sets it.
As you can see from the output, the printing out of the list elements ends at element six because we are telling the program to stop the execution when the for loop reaches the element seven. We do this using the break statement. In case there was no element seven in the list, the else statement would be executed.
A break statement can also be used in the same way inside a while loop.
Here is an advanced example of its usage:
var = 10 while var > 0:
print ("Current value :", var) var -= 1
Break
The list ‘breaks’
after number 6
if var == 5:
break
Tip: -= in the fourth line of the sample code above is the Subtract and Assignment operator. It will subtract 1 from the current value of var and then assign this new calculated value to var.
Notice that here we are using a decrementing while loop that starts at 10 and ends at zero. The loop block prints out some text together with the value of variable var for each iteration. Normally, the printing out would go from 10 down to zero and then stop if there was no break clause inside the loop, but in this case, this is not true. The break clause will terminate the printing out at element six. Here is the output:
Figure 4.14: Numbers printed out from 10 down to six where the break clause terminates the loop
On the other hand, the continue statement is used to return the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of
the loop and moves the control back to the top of the loop. Simply put, the continue statement
continues the execution of the block. Here is the example:
list = [1,2,3,4,5,6,7,8,9]
4.4 Break, Continue, and Else 7373 In this case we are telling the program to continue the expression even if the enumeration reaches the element seven. The output of the previous code would be:
Figure 4.15: Elements printed out from the for loop block
The else statement itself has its own role inside a loop. When else is used inside a for loop, it is executed when the loop has exhausted iterating through the list. When else is used inside a while loop, the else statement is executed when the condition becomes false.
Both break and continue are useful functionalities that give more control to the work flow.
Questions for Review
1. What would the following code do when executed?
a = 0
while a < 100:
print (a) a += 2
a. Print out numbers from zero to 100.
b. Print out zero and two.
c. Print out even numbers that fall between zero and 100.
d. Display an error message.
2. What does the range functionality do?
a. Generates a list.
b. Defines the looping method.
c. Generates a tuple.
d. None of the above.
3. The for loop is commonly used to:
a. Print out elements.
b. Execute some code until a condition is met.
c. Iterate through lists, tuples and strings.
d. Iterate through integers.
4. What is true about try and except?
a. The expression under try is executed when there is an exception.
b. The expression under except is executed when the expression under try experiences an error.
c. Neither of the expressions under try or except are executed when an IOError occurs.
d. All above are false.
5. What happens when the condition above the break code line is not met?
a. The continue part is executed.
b. The line under break is not executed.
c. The line under break is executed.
d. The whole program breaks.
Questions for Review
75 Final Lab Exercises 75
C
hapTer4 l
abe
XerCiseYou may have heard of the Fibonacci Sequence. It is a sequence of numbers where the next number is found by adding the previous two numbers together.
It follows this format:
Fn = Fn – 2 + Fn -1
with initial values of F0 = 0 and F1 = 1
This sequence is truly something amazing, and is found throughout nature. By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two. There is also a geometrical representation of the sequence through a spiral. The area of each of the squares is equal to a number of the sequence.
Figure 4.16: A Geometric representation of the Fibonacci sequence
Your task is to create a sequence of numbers for the Fibonacci sequence and stop at the first number that is greater than 100.
l
abs
oluTionf0 = 0 f1 = 1
set = False while True:
fn = f0 + f1 f0 = f1
f1 = fn
if (fn > 100):
set = True else:
set = False print(fn)
if (set == True):
break
77 Final Lab Solutions 77 The above code was input and executed in Eclipse as file fibonacci22.py.
This is how the code and its output would look:
Figure 4.17: Lab solution (upper part) and the generated Fibonacci Sequence output
C
hapTer4 s
ummaryIn this chapter you were introduced to the looping functionality.
We discussed how looping comes to be very important due to its abilities to repeatedly execute multiple statements dependent on some conditions.
We explained both the while and the for loop. You should know that the for loop is specifically used when iterating through elements of lists, tuples, or strings. The while loop is more condition-oriented and less explicit in terms of the element it iterates.
We also went further and learned about error handling in Python in the sense of how to give better control to the encountered errors via the try and except functionality.
Furthermore, you were introduced to the break and continue tools that are used to better control the flow of the looping.
In the next chapter we will be talking about lists more in-depth.
We will discuss list manipulation issues such as modifying, deleting, adding and sorting list elements and we will perform actions between different lists. You will get a better overall understanding of the usefulness of lists.
79