Question

I am a beginner Python programmer (Python 3) and I just made my first real working program. I encounter an issue with the try: except: part (ln 63), I can't manage to trigger the range_error condition in the usr_input() function. I'm probably not using exceptions the right way.

from random import randint

def gen_num():
    magic_num = randint(1,100)
    return magic_num

def usr_input(range_error = False):
    if range_error == True: # If number is out of range, displays additionnal warning message
        print("Make sure you enter a number between 1 and 100 !")
    usr_num_guess = input("Please enter an integer between 1 and 100 : ")
    return int(usr_num_guess)

def play_again():
    # We ask the user to choose if he wants to play again or not (yes / no)
    yes = set(['yes','y','ye','yeah',''])
    no = set(['no','n'])

    usr_choice = input("Do you wish t play again ? (Y/n):").lower()
    if usr_choice in yes:
        return True
    elif usr_choice in no:
        return False
    else:
        sys.stdout.write("Please write 'yes' or 'no'")

def player_level_initialize():
    # Setting up the user's desired level
    easy_level = set(['easy',1])
    med_level = set(['medium','med',2,''])
    hard_level = set(['hard','difficult',3])

    level_choice = input("Please select your level (easy,MED,hard) :").lower()

    if (level_choice in easy_level):
        return "easy"
    elif (level_choice in med_level):
        return "med"
    elif (level_choice in hard_level):
        return "hard"
    else:
        sys.stdout.write("Please write 'easy', 'med' or 'hard'")

print("Hello and Welcome to this awesome game !")
player_name = input("Please enter your name : ")
level = player_level_initialize()
keep_playing = True
usr_score = 0

while (keep_playing == True):

        num_to_guess = gen_num()
        num_of_attempts = 1
        too_m_attempts = False
        max_number_of_attempts = {
            "easy":10,
            "med":6,
            "hard":3
        }
        usr_num_guess = usr_input()

        while (too_m_attempts == False or usr_num_guess != num_to_guess):
            if (num_of_attempts < max_number_of_attempts[level]):
                try:
                    (usr_num_guess >= 1 and usr_num_guess < 100)
                except:
                    usr_num_guess = usr_input(True) # If the input number is out of range, the player gets a warning message + new input
                else:
                    if (usr_num_guess != num_to_guess):
                        if (usr_num_guess < num_to_guess):
                            print("It's more !")
                        else:
                            print("It's less !")
                        num_of_attempts += 1
                        usr_num_guess = usr_input()
                    elif (usr_num_guess == num_to_guess):
                        usr_score += 1
                        print("Good job", player_name, "you found the magic number in only", num_of_attempts, "attempts ! It was", num_to_guess, "You have a current score of", usr_score)
            else:
                print("Sorry, too many attempts ! The magic number was", num_to_guess)
                too_m_attempts = True

        keep_playing = play_again()

print("Thank you ! I hope you enjoyed the game !")
Was it helpful?

Solution

What you need is an if block instead of a try-except block:

if not (usr_num_guess >= 1 and usr_num_guess < 100):
    usr_num_guess = usr_input(True) # If the input number is out of range, the player gets a warning message + new input

The code in the except part will only be executed if the line (usr_num_guess >= 1 and usr_num_guess < 100) raises an exception.

On the use of exception, when you write

try:
    ...
except:
    ...

the code will catch every possible exception and execute th code in the except block which is supposed to fix the situation. This is probably not what you want most of the time. For example, mis-spelling a variable (e.g. usr_num_guesss) will raise a NameError, and whatever user_input() do will not fix the error -- it is an entirely different problem already than an out-of-range input. You should only catch and handle the exceptions that can be handled by your code, such as:

except ValueError:
    ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top