user3589979
user3589979

Reputation: 11

Beginner 'Guess my number' program. while loop not breaking when correct number guessed or when out of guesses

So I'm learning python and I'm trying to code a simple guess my number game where you only have 5 guesses or the game ends. Im really having trouble with the while loop not recognising that the number has been guessed or the guess limit has been reached. Is there a better way of formatting my functions also. Thanks for any and all help, first time using this site.

# Guess my number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money

import random

GUESS_LIMIT = 5

# functions
def display_instruct():
    """Display game instructions."""
    print("\tWelcome to 'Guess My Number'!")
    print("\nI'm thinking of a number between 1 and 100.")
    print("Try to guess it in as few attempts as possible.")
    print("\nHARDCORE mode - You have 5 tries to guess the number!\n")


def ask_number(question, low, high, step = 1):
    """Ask for a number within a range."""
    response = None
    while response not in range(low, high, step):
        response = int(input(question))
    return response


def guessing_loop():
    the_number = random.randint(1, 100)
    guess = ask_number("\nTake a guess:", 1, 100)
    tries = 1

    while guess != the_number or tries != GUESS_LIMIT:
        if guess > the_number:
            print("Lower...")
        else:
            print("Higher...")

        guess = ask_number("Take a guess:", 1, 100)
        tries += 1

    if tries == GUESS_LIMIT:
        print("\nOh no! You have run out of tries!")
        print("Better luck next time!")
    else:
        print("\nYou guessed it! The number was", the_number)
        print("And it only took you", tries, "tries!")


def main():
    display_instruct()
    guessing_loop()


# start the program
main()
input("\n\nPress the enter key to exit")

Upvotes: 1

Views: 349

Answers (2)

skeptics
skeptics

Reputation: 23

Or you can break your cycle explicitly with break statement. But previous answer is more correct in a sense you should really understand conditions you're setting for the loop.

Upvotes: 0

Bill the Lizard
Bill the Lizard

Reputation: 405765

Your while condition will be true as long as you haven't hit the guess limit.

while guess != the_number or tries != GUESS_LIMIT:

You should join those conditions with and, not or. The way you have it now, the entire condition will be true because tries != GUESS_LIMIT is true, even if guess != the_number is false.

Upvotes: 2

Related Questions