Home > Back-end >  How to fix 'if' statement activating with 'and' arguments when 'else'
How to fix 'if' statement activating with 'and' arguments when 'else'

Time:11-13

Neophyte here. I'm trying to apply what I've learned so far in Python to create better understandings of how things work so far. I'm combining someone's number guessing game with freecodecamp's guessing game. When the 'guess limit' is met, I lose correctly. However when the number is entered correctly, the user still 'loses'.

For example in the code below, I call the function with x = 5, and when I 'guess' 5, I still receive the 'if limit' action when I want it to be the 'else' action.

I've tried several variations to see if I could figure it out, but to no avail. Any support would be greatly appreciated. If there's a link or article you could guide me to, that'd be great.

def numguess(x):
    number = x
    guess = 0
    guess_count = 1
    guess_limit = 5
    limit = False

    while guess != number and not(limit):
        guess = int(input("\nGuess the number: "))
        if guess < number and guess_count <= 4:
            print("too low")
            guess_count  = 1
        elif guess > number and guess_count <= 4:
            print("too high")
            guess_count  = 1
        else:
            limit = True
        
    if limit:
        print("you lose")
    else:
        print("you win")
numguess(5) 

CodePudding user response:

You can simplify your code, like this:

def numguess(x):
    number = x
    guess = 0
    guess_count = 1
    guess_limit = 5

    while guess != number and guess_count <= guess_limit:
        guess = int(input("\nGuess the number: "))
        if guess < number:
            print("too low")
            guess_count  = 1
        elif guess > number:
            print("too high")
            guess_count  = 1
        
    if guess_count <= guess_limit:
        print("you win")
    else:
        print("you loose")
numguess(5)

or, if you really want to use the limit variable:

def numguess(x):
    number = x
    guess = 0
    guess_count = 1
    guess_limit = 5
    limit = False

    while guess != number and not(limit):
        guess = int(input("\nGuess the number: "))
        if guess < number:
            print("too low")
            guess_count  = 1
        elif guess > number:
            print("too high")
            guess_count  = 1
        limit = guess_count > guess_limit
        
    if limit:
        print("you loose")
    else:
        print("you win")
numguess(5)
  • Related