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 !")
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
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)
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)