0
import random
from random import randint

number = randint(1, 500)
guess = input("The computer has chosen a random number. Guess the number: ")
guess = int(guess)

while guess == number:
    print("Congrats, you have won")
    break

if guess > number:
    print("Lower")

if guess < number:
    print("Higher")

This code only allows the user to input one guess and then the program ends. Can someone help me fix this

3 Answers3

2

You should think about your loop condition.

  • When do you want to repeat? This is the loop condition
    • When the guess is not correct. guess != number
  • What do you want to repeat? Put these inside the loop
    • Asking for a guess guess = int(input("Your guess: "))
    • Printing if it's higher or lower if guess > or < number: ...
  • What don't you want to repeat?
    • You need this before the loop
      • Deciding the correct number.
      • Setting the initial guess so the loop is entered once
    • You need this after the loop
      • Printing the "correct!" message, because you only exit the loop once the guess is correct

So we have:

number = random.randint(1, 100)
guess = 0

while guess != number:
    guess = int(input("Your guess: "))
    if guess > number:
       print("Lower")
    elif guess < number:
       print("Higher")

print("Correct!")
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
1

Right now, your while loop is useless as once you are in it you break immediately. The rest of the code is not in a loop.

You should rather have an infinite loop with all your code, and break when there is a match:

from random import randint

number = randint(1, 500)

while True:                    # infinite loop
    guess = input("The computer has chosen a random number. Guess the number: ")
    guess = int(guess)         # warning, this will raise an error if
                               # the user inputs something else that digits

    if guess == number:        # condition is met, we're done
        print("Congrats, you have won")
        break

    elif guess > number:       # test if number is lower
        print("Lower")

    else:                      # no need to test again, is is necessarily  higher
        print("Higher")
mozway
  • 194,879
  • 13
  • 39
  • 75
0

You must take input in the loop, because the value for each step has to be updated .

from random import randint


number = randint(1, 500)

while True:
    guess = input("The computer has chosen a random number. Guess the number: ")
    guess = int(guess)
    
    
    if guess == number:
        print("Congrats, you have won")
        break

    if guess > number:
        print("Lower")

    if guess < number:
        print("Higher")
Amir Aref
  • 361
  • 1
  • 5