< previous | Table of Contents | järgmine > |
5.6 COMMON ERRORS
ITERATING OVER TOO MANY OR TOO FEW ELEMENTS
This error occurs when the loop iterates one time too many or one time too few. It can occur both with while
and for
loops.
As an example with while
loops, say we want to sum all the numbers from 1 to 10, including 10. However, as we've used <
instead of <=
, we calculate the sum of the first 9 numbers instead.
In the case of for
loops, for example, this can occur when iterating over a list
of items combining the range()
and len()
functions. This is a common way of iterating over lists, which we will cover in more depth in the Lists chapter. However, here's an example to illustrate.
The list contains six elements, but range(len(elements) - 1) translates to range(5), meaning that the loop only iterates over the indices 0, 1, 2, 3, 4 but misses the last element at index 5.
Also, with for loops, we might accidentally iterate over one index too many, this would lead to an IndexError
as there are no more elements within the list that could exist at that particular index.
INFINTE LOOPS
We've covered this now a few times, but as a reminder, an infinite loop is a loop that never ends because the terminating condition is never met or is incorrectly defined. However, as mentioned before, in certain conditions, we want the loop to run infinitely until a condition is met and a break
statement triggers an exit from the loop.
The following example shows a while
loop where we've forgotten to increment the i
, and thus, the condition never reaches a value larger than or equal to 5, running infinitely.
i = 0 while i < 5: print(i)
UNINITIALIZED VARIABLES
This is an error that results from trying to use an iterator outside its scope without it being initialized first. Hence, we would get a NameError
. This is how it would show up in Thonny.
< previous | Table of Contents | järgmine > |