Arvutiteaduse instituut
  1. Kursused
  2. 2025/26 sügis
  3. Programmeerimise alused (MTAT.03.236)
EN
Logi sisse

Programmeerimise alused 2025/26 sügis

  • 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

  • Arvutiteaduse instituut
  • Loodus- ja täppisteaduste valdkond
  • Tartu Ülikool
Tehniliste probleemide või küsimuste korral kirjuta:

Kursuse sisu ja korralduslike küsimustega pöörduge kursuse korraldajate poole.
Õppematerjalide varalised autoriõigused kuuluvad Tartu Ülikoolile. Õppematerjalide kasutamine on lubatud autoriõiguse seaduses ettenähtud teose vaba kasutamise eesmärkidel ja tingimustel. Õppematerjalide kasutamisel on kasutaja kohustatud viitama õppematerjalide autorile.
Õppematerjalide kasutamine muudel eesmärkidel on lubatud ainult Tartu Ülikooli eelneval kirjalikul nõusolekul.
Courses’i keskkonna kasutustingimused