Home > Software engineering >  How to fix infinite loop in guess a number function?
How to fix infinite loop in guess a number function?

Time:10-19

I'm working on a guess a number function where the user thinks of a random integer and the computer generates a guess. If the user's number is higher, they type and if it's lower they type - I'm having trouble with this, when I run the code it goes into an infinite loop. I also need to print the computer's initial guess but when I put it above the loop the code wouldn't run.

 def guess_a_number():
   lower = 0
   higher = 100
   num = randint(lower, higher)
   x = input("Higher( ), lower(-), or correct(y)?")

   while x != "y":
     if x == " ":
       lower  = 1
       print(num)
     elif x == "-":
       higher = higher - 1
       print(num)
   print("yay :D")
   print(num)

CodePudding user response:

This is the problem:

while x != "y":

You only declared x once, so x never changes again, so the while loop never breaks.

So depending on what you want to accomplish, inorder to break out of the while loop, you either have to:

  • Update the variable x so the condition x != "y" becomes False
  • Check for any other condition

CodePudding user response:

Your loop body never changes x, so the condition will either never be true, or always be true.

You need to prompt again for x inside the loop.

You could just use an infinite loop and break on 'y'.

def guess_a_number():
  lower, higher = 0, 100

  while True:
    num = randint(lower, higher)
    print(f"Is it {num}?")
    x = input("Higher( ), lower(-), or correct(y)?")

    if x == 'y':
      print('Yay!')
      break

    if x == ' ': lower = num   1
    elif x == '-': higher = num - 1

You also want to use the number the computer "guesses" to set your bounds, rather than just incrementing or decrementing them. If it prompts with 8 and you say lower, on your first try it could try 90 next, and that doesn't make much sense.

  • Related