Skip to main content
deleted 109 characters in body
Source Link
Reinderien
  • 71.2k
  • 5
  • 76
  • 257

It seems like on your last line, you assumed that answer would contain the user's name, but it doesn't.

guesses = guesses + 1 can be guesses += 1.

It seems like on your last line, you assumed that answer would contain the user's name, but it doesn't.

guesses = guesses + 1 can be guesses += 1.

guesses = guesses + 1 can be guesses += 1.

Source Link
Reinderien
  • 71.2k
  • 5
  • 76
  • 257

to high should be too high.

guessNumber should be guess_number by PEP8.

Im should be I'm.

It seems like on your last line, you assumed that answer would contain the user's name, but it doesn't.

guesses = guesses + 1 can be guesses += 1.

A good program separates its input/output from its business logic, among other reasons so that you can unit test the logic, and so that you can swap out the interface with a different one. There are many ways to do this; I demonstrate one below. This uses some mid-level concepts that will probably pull you out of beginner material, but I consider that healthy.

from random import randint
from typing import Iterator, Iterable

GUESS_LOWER = 1
GUESS_UPPER = 20


def get_guess() -> int:
    """
    Keep asking the user for a guess until we get one that is numeric and within the guess bounds.
    """
    while True:
        try:
            guess = int(input('Take a guess: '))
        except ValueError:
            print('Invalid number')
            continue

        if not (GUESS_LOWER <= guess <= GUESS_UPPER):
            print('Number out of range')
        else:
            return guess


def calculate_game(guesses: Iterable[int], answer: int) -> Iterator[int]:
    """
    Business logic for guessing.

    :param guesses: An infinite iterator of user guess integers.
    :param answer: The integer the user is trying to guess
    :return: An iterator of -1, 0 or 1, meaning too-low, correct or too-high.
    """

    for guess in guesses:
        diff = guess - answer
        if diff == 0:
            yield 0
            break
        yield diff // abs(diff)


def print_game(answer: int) -> int:
    """Run the game with console input/output."""

    # This makes an iterator that infinitely yields the return value of get_guess().
    guesses = iter(get_guess, None)

    responses = {
        -1: 'That is too low!',
        0: 'Good job!',
        1: 'That is too high!',
    }

    # enumerate() gives us pairs: the number of guesses (starting at 1),
    # and the diff from calculate_game().
    for guess_count, diff in enumerate(calculate_game(guesses, answer), start=1):
        print(responses[diff])
    return guess_count


def main() -> None:
    print(f"I'm thinking of a number between {GUESS_LOWER} and {GUESS_UPPER}.")
    answer = randint(GUESS_LOWER, GUESS_UPPER)
    guess_count = print_game(answer)
    print(f'You guessed my number in {guess_count} guesses!')


if __name__ == '__main__':
    main()