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
  • Grading
  • Links

Before session 4

Loops and iterations

Work through topics from the reading materials or watch the videos.

Test

Go to Moodle and take the fourth test.

Homework

The deadline for homework is Monday. Nevertheless, you can start with homework already before the session.

This week we are going to get an insight into loops (while and for).

Example 1

In many cases, it is possible to solve an exercise using both the while and for loops. The following programs calculate the sum of the figures from 1 to 9. The first program contains the for-loop and the second one uses the while-loop.

print("Finding sum with for loop")
sum1 = 0
for i in [1,2,3,4,5,6,7,8,9]:
    sum1 = sum1 + i
    print("Sum so far", sum1)
print("Sum of numbers 1-9 is", sum1)

print("Finding sum with while loop")
sum2 = 0
a = 1
while a < 10:
    sum2 = sum2 + a
    print("Sum so far", sum2)
    a += 1
print("Sum of numbers 1-9 is", sum2)

Example 2

The following program is a modified example from last week - The maximum program. The present program contains a loop which repeatedly asks the user for numbers and outputs the greatest of these numbers. The program continues asking until the user enters “done” instead of the first number. If the user enters something else but integers, the program processes the error using try and except, prints out a message and skips to the next number.

def maximum(a, b):
    if a < b:
        return b
    else:
        return a

while True:
    line = input("Enter the first number or word 'done': ")
    if line == 'done':
        break
    line2 = input("Enter the second number: ")
    try:
        x = int(line)
        y = int(line2)
        m = maximum(x, y)
        print("The maximum of numbers", x, "and", y, "is", m)
    except:
        print("Please enter a number")

Homework exercises

  • 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