Example solutions for script 04_looping exercise block 7

Exercise 7.3

import random

to_guess = random.randint(0, 100)

guesses = 0

while True:
    user_guess = int(input("your guess ? "))
    guesses = guesses + 1
    if user_guess < to_guess:
        print("your guess is to low")
    elif user_guess > to_guess:
        print("your guess is to high")
    else:
        break
print("you needed", guesses, "guesses !")
your guess ? 50
your gess is to high
your guess ? 25
your gess is to high
your guess ? 12
your gess is to high
your guess ? 6
your gess is to high
your guess ? 3
your gess is to high
your guess ? 2
your gess is to high
your guess ? 1
you needed 7 guesses !

Exercise 7.5

import random

while True:

    to_guess = random.randint(0, 100)
    print("to cheat, the secret number is", to_guess)

    guesses = 0

    while True:
        user_guess = int(input("your guess ? "))
        guesses = guesses + 1
        if user_guess < to_guess:
            print("your guess is to low")
        elif user_guess > to_guess:
            print("your guess is to high")
        else:
            break
    print("you needed", guesses, "guesses !")
    
    print()
    answer = input("do you want to play again (y/n) ? ")
    if answer == "n":
        break
to cheat, the secret number is 64
your guess ? 63
your guess is to low
your guess ? 80
your gess is to high
your guess ? 64
you needed 3 guesses !

do you want to play again (y/n) ? y
to cheat, the secret number is 17
your guess ? 20
your gess is to high
your guess ? 17
you needed 2 guesses !

do you want to play again (y/n) ? n

Exercise 7.6

The obvious approach is to generate a random number in range 0 ... 3 and then use branching to map this number to one of respective the characters / symbols.

The following solutions uses indexing instead and is shorter. Again we use the += abbreviation:

import random
sequence = ""
for i in range(10):
    sequence += "ATGC"[random.randint(0, 3)]
print(sequence)
TATCCCTCTC

Repetition exercise

The following solution not only computes if a given number is prime but also reports a divisior if found:

If we find a divisor $a$ of $n$, that is $n = a \cdot b$ and $a \gt \sqrt{n}$ then $b \lt \sqrt{n}$.

n = 2047

divisor = 2
is_prime = True

while divisor * divisor <= n:
    if n % divisor == 0:
        is_prime = False
        break
    divisor = divisor + 1
    
if is_prime:
    print("given number", n, "is prime")
else:
    print("given number", n, "is not prime, found divisor", divisor)
given number 2047 is not prime, found divisor 23