Institute of Computer Science
  1. Courses
  2. 2025/26 fall
  3. Introduction to Programming (MTAT.03.236)
ET
Log in

Introduction to Programming 2025/26 fall

  • Home Page
  • Introduction
  • Expressions
  • Conditional Execution
  • Functions
  • Iterations
  • Strings
  • Files
  • Lists
  • Graphics?
< previousTable 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.

< previousTable of Contents järgmine >

  • Institute of Computer Science
  • Faculty of Science and Technology
  • University of Tartu
In case of technical problems or questions write to:

Contact the course organizers with the organizational and course content questions.
The proprietary copyrights of educational materials belong to the University of Tartu. The use of educational materials is permitted for the purposes and under the conditions provided for in the copyright law for the free use of a work. When using educational materials, the user is obligated to give credit to the author of the educational materials.
The use of educational materials for other purposes is allowed only with the prior written consent of the University of Tartu.
Terms of use for the Courses environment