After entering each number
by the user, the program should report whether the hidden number is greater or
less. The program should count the number of attempts and after
how the number is guessed – display the corresponding message.
import random
number = int (random.randint (1,100) )
attempts = 0
guess = input ('Guess the value from 1 to 100.')
while guess != number:
if guess == number:
print ('Congratulations, you guessed it right!')
elif guess < number:
print ('Your guess is less than the number.')
elif guess > number:
print ('Your guess is bigger than the number.')
attempts += 1
guess = input ('Guess the value from 1 to 100.')
print ('The amount of attempts:', attempts)
>Solution :
- No need to convert
numberto anint, because it’s already anint. - You do however need to convert
guessto anintif you want to be able to compare it tonumber! Note that this will raise aValueErrorif the user inputs a value that can’t be converted to anint. - Make sure to indent the code that goes inside the
whileloop. - You can make the loop simpler (e.g. no need to assign
guessbefore the loop starts) by usingwhile True:and just usingbreakwhen it’s time to end the loop.
import random
number = random.randint(1, 100)
attempts = 0
while True:
try:
guess = int(input("Guess the value from 1 to 100."))
except ValueError:
print("Try guessing a number.")
continue
attempts += 1
if guess < number:
print("too low")
elif guess > number:
print("too high")
else:
print("just right!")
break
print(f"Total attempts: {attempts}")