Example solutions for script 04_looping exercise block 1

Exercise 1.2

n = 3
acc = 0

for j in range(1, n + 1):
    acc += j ** 2
    
print("the sum of the squares of the first", n, "natural numbers is", acc)
the sum of the squares of the first 3 natural numbers is 14

Exercise 1.3

n = 3
acc = 1

for j in range(1, n + 1):
    acc = acc * j
    
print("the product of the first", n, "natural numbers is", acc)
the product of the first 3 natural numbers is 6

Exercise 1.4

We start looping with $0$ because our first summand is $1$ which is $2^0$, we exponents $0$ to $10$:

n = 11
acc = 0

for j in range(n):
    acc += 2 ** j
    
print(acc)
2047

Exercise 1.5 + 1.6 + 1.7

h = int(input("height of triangle ? "))
print()  # blank line
for n in range(1, h + 1):
    print("*" * n)
height of triangle ? 9

*
**
***
****
*****
******
*******
********
*********
h = int(input("height of triangle ? "))
print() # blank line
for n in range(h):
    n_spaces = h - n - 1
    n_stars = 2 * n + 1
    print(n_spaces * " " + n_stars * "*")
height of triangle ? 12

           *
          ***
         *****
        *******
       *********
      ***********
     *************
    ***************
   *****************
  *******************
 *********************
***********************