Search code examples
pythonwhile-loopconditional-statements

Problem with number guessing game: Guesses arent getting substacted or condition isnt implemented?


For some reason, either my guesses arent being subtracted or the condition in the while loop is not implemented somehow. I've tried loads of things but nothing worked. Heres the code:

def guess_func():
    numberrange1 = random.randint(1, 100)
    rightnumber1 = False
    guesses = 3
    while rightnumber1 != True or guesses != 0:
        numberguess1 = int(input('The range is set. Now guess: '))
        if numberguess1 == numberrange1:
            print('Thats the right number! Congrats!')
            rightnumber1 = True
        elif numberguess1 != numberrange1:
            guesses = guesses - 1
            if numberrange1 > numberguess1:
                print('Higher!')
            elif numberrange1 < numberguess1:
                print('Lower!')
        else:
            print('This number is wrong or you entered something else.')

Solution

  • The if condition is the problem:

    while rightnumber1 != True or guesses != 0:
    

    This loop will continue running as long as they haven't guessed the correct number, OR they have no guesses remaining.

    But that logic is wrong -- you want the loop to keep running only as long as BOTH of those conditions are true!

    If they have guessed correctly, then you want the loop to stop immediately; you don't care how many guesses they have remaining.

    And if they have no guesses remaining, then you also want the loop to stop immediately; you don't care if they have guessed correctly.

    You want to use an AND condition here, not an OR.

    while rightnumber1 != True and guesses != 0: