Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Write a program that generates an integer between 1 and 100 and prompts the user to guess it

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • No need to convert number to an int, because it’s already an int.
  • You do however need to convert guess to an int if you want to be able to compare it to number! Note that this will raise a ValueError if the user inputs a value that can’t be converted to an int.
  • Make sure to indent the code that goes inside the while loop.
  • You can make the loop simpler (e.g. no need to assign guess before the loop starts) by using while True: and just using break when 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}")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading