Example solutions for script 04_looping exercise block 2

Exercise 2.2

n = 7
acc = 0
for i in range(1, n + 1):
    if i % 2 == 0:
        acc += i
        
print(acc)
12

Exercise 2.3

This is a solution for approach B:

n = 7
sum_even = 0
sum_odd = 0

for i in range(1, n + 1):
    if i % 2 == 0:
        sum_even += i
    else:
        sum_odd += i
        
print("sum of even numbers is", sum_even)
print("sum of odd numbers is", sum_odd)
sum of even numbers is 12
sum of odd numbers is 16

Exercise 2.5

If we write print(..., end=" ") we do not separate the output of following print statements with a new line, but with the given :

for i in range(1, 31):
    if i % 15 == 0:
        print("fizz buzz", end=" ")
    elif i % 3 == 0:
        print("fizz", end=" ")
    elif i % 5 == 0:
        print("buzz", end=" ")
    else:
        print(i, end=" ")
1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizz buzz 16 17 fizz 19 buzz fizz 22 23 fizz buzz 26 fizz 28 29 fizz buzz 

Hint: replace the end parameter with aribraty strings and see how the output changes !

Exercise 2.6

for i in range(1500, 2001):
    if i % 7 == 0 and i % 13 == 0:
        print(i)
1547
1638
1729
1820
1911

Exercise 2.7

Read nip as n_is_prime (n_is_prime is the better name, but I did not make it to obvious what the program computes).

The program checks for a given $n$ if there is an i in range $2 \le i \lt n$ which is a divisor of $n$. Eventually it prints True if such a divisor was not found and False else. So it checks if $n$ is a prime number !

for n in range(2, 20):
    nip = True
    for i in range(2, n):
        if n % i == 0:
            nip = False
    if nip:
        print(n)
2
3
5
7
11
13
17
19