#!/usr/bin/python3 '''A simple guess-my-number game''' import sys import random def to_valid_number(number_string, max_number): # pylint: disable=superfluous-parens ''' Convert string to a number between 1 and max_number. Raise ValueError if invalid ''' number_string_stripped = number_string.strip() if '.' in number_string: print('That is not a whole number.') raise ValueError('Not a whole number 1') try: # technically, this will reject decimals too number = int(number_string_stripped) except ValueError: print('That is not a whole number.') raise ValueError('Not a whole number 2') if number < 1: print('That number is out of range; it is too low. Please enter a number between 1 and {}'.format(max_number)) raise ValueError('Too low') if number > max_number: print('That number is out of range; it is too high. Please enter a number between 1 and {}'.format(max_number)) raise ValueError('Too high') return number def display_guesses(low_guesses, high_guesses): # pylint: disable=superfluous-parens '''Display the low and high guesses in a concise way''' guesses = [] for guess in sorted(low_guesses): guesses.append(str(guess)) guesses.append('|') for guess in sorted(high_guesses): guesses.append(str(guess)) print('Your guesses: ' + ' '.join(guesses)) def main(): # pylint: disable=superfluous-parens '''Main function''' low_guesses = [] high_guesses = [] num_guesses = 0 max_number = 100 my_number = random.randint(1, max_number) print("Let's play \"guess my number\".\n") while True: print("I'm thinking of a number between 1 and {}.".format(max_number)) print("What is your guess?") while True: line_of_input = sys.stdin.readline() try: user_guess = to_valid_number(line_of_input, max_number) except ValueError: print('That was an illegal input. Please try again.') else: break if user_guess == my_number: num_guesses += 1 print('That is correct!') print('You got it in {} guesses.'.format(num_guesses)) break elif user_guess < my_number: num_guesses += 1 low_guesses.append(user_guess) display_guesses(low_guesses, high_guesses) print('Too low. Please try again.\n') elif user_guess > my_number: num_guesses += 1 high_guesses.append(user_guess) display_guesses(low_guesses, high_guesses) print('Too high. Please try again.\n') else: raise AssertionError('This should never happen 2') print('\nThank you for playing.') main()