0

I want this number guessing game to be able to catch every possible exception or error the user enters. I've successfully prevented the use of strings when guessing the number, but I want the console to display a custom message when a float is entered saying something along the lines of "Only whole numbers between 1-20 are allowed". I realize my exception would work to catch this kind of error, but for learning purposes, I want to specifically handle if the user enters a float instead of an int. From what I could find online the isinstance() function seemed to be exactly what I was looking for. I tried applying it in a way that seemed logical, but when I try to run the code and enter a float when guessing the random number it just reverts to my generalized exception. I'm new to Python so if anyone is nice enough to assist I would also appreciate any criticism of my code. I tried making this without much help from the internet. Although it works for the most part I can't get over the feeling I'm being inefficient. I'm self-taught if that helps my case lol. Here's my source code, thanks:

import random
import sys


def getRandNum():
    num = random.randint(1,20)
    return num

def getGuess(stored_num, name, gameOn = True):
    while True:
        try:
            user_answer = int(input("Hello " + name + " I'm thinking of a number between 1-20. Can you guess what number I'm thinking of"))
            while gameOn:
                if user_answer >= 21 or user_answer <=0:
                    print("That is not a number between 1-20. Try again.")
                    user_answer = int(input())
                elif isinstance(user_answer, int) != True:
                    print("Only enter whole numbers. No decimals u cheater!")
                    user_answer = int(input())
                elif user_answer > stored_num:
                    print("That guess is too high. Try again " + name + " !")
                    user_answer = int(input())
                elif user_answer < stored_num:
                    print("That guess is too low. Try again " + name + " !")
                    user_answer = int(input())
                elif user_answer == stored_num:
                    print("You are correct! You win " + name + " !")
                    break
        except ValueError:
            print("That was not a number, try again")

def startGame():
    print("Whats Your name partner?")
    name = input()
    stored_num = getRandNum()
    getGuess(stored_num, name)


def startProgram():
    startGame()


startProgram()


while True:
    answer = input("Would you like to play again?  Type Y to continue.")
    if answer.lower() == "y":
        startProgram()
    else:
        break

quit()

1 Answers1

0

The only thing that needs be in the try statement is the code that checks if the input can be converted to an int. You can start with a function whose only job is to prompt the user for a number until int(response) does, indeed, succeed without an exception.

def get_guess():
    while True:
        response = input("> ")
        try:
            return int(response)
        except ValueError:
            print("That was not a number, try again")

Once you have a valid int, then you can perform the range check to see if it is out of bounds, too low, too high, or equal.

# The former getGuess
def play_game(stored_num, name):

    print(f"Hello {name}, I'm thinking of a number between 1-20.")
    print("Can you guess what number I'm thinking of?")

    while True:
        user_answer = get_guess()
        
        if user_answer >= 21 or user_answer <=0:
            print("That is not a number between 1-20. Try again.")
        elif user_answer > stored_num:
            print(f"That guess is too high. Try again {name}!")
        elif user_answer < stored_num:
            print(f"That guess is too low. Try again {name}!")
        else:  # Equality is the only possibility left
            print("You are correct! You win {name}!")
            break
chepner
  • 497,756
  • 71
  • 530
  • 681