Search code examples
pythonloopsif-statementwhile-loopinfinite-loop

Python 3.4 :While loop not looping


Python loop isn't wanting to loop back if the user's guess is greater than or less than the randomly generated value. It either exits the loop or creates an infinite loop. Where am I going wrong?

import random

correct = random.randint(1, 100)
tries = 1
inputcheck = True
print("Hey there! I am thinking of a numer between 1 and 100!")
while inputcheck:
    guess = input("Try to guess the number! " )
    #here is where we need to make the try statement
    try:
        guess = int(guess)
    except ValueError:
        print("That isn't a number!")
        continue
    if 0 <= guess <= 100:
        inputcheck = False
    else:
        print("Choose a number in the range!")
        continue
    if guess == correct:
        print("You got it!")
        print("It took you {} tries!".format(tries))
        inputcheck = False
    if guess > correct:
        print("You guessed too high!")
        tries = tries + 1
    if guess < correct:
        print("You guessed too low!")
        tries = tries + 1

    if tries >= 7:
        print("Sorry, you only have  7 guesses...")
        keepGoing = False

Solution

  • The problem is with this line:

    if 0 <= guess <= 100:
        inputcheck = False
    

    This will terminate the loop whenever the user enters a number between 0 and 100. You can rewrite this part as:

    if not 0 <= guess <= 100:
        print("Choose a number in the range!")
        continue