Python Python Basics (2015) Number Game App Number Game Takeaways

how do I try: a negative number in try: except: else:

This is the "Extra credit" for the number game. I'm still working on it. It handles an empty string or string ok with the proper message. And it does what I intended. However if I enter a negative number, it just freaks out. How could I get it to handle a negative with an appropriate message?

  • btw, I'm sure there's faster or more clever ways to do this...I'm just exploring.
import random
a = 1
my_guess = input("Pick a number 1 to ~, let the computer guess it: ")
# my_guess = int(my_guess)
# if my_guess < 1:
    my_guess = int(my_guess)
except ValueError:
    print("ERROR: enter a number ie: 1,2,3...")
# here, after the exception: start the game back at the beginning

    b = my_guess
    pc_guess = random.randint(a, b)

    lose = True
    tries = 1
    while lose:
        if pc_guess < my_guess:
            pc_guess += 1
            tries += 1
            lose = False
I picked {}. It took {} tries for the computer to guess it.
    """.format(my_guess, tries ))

1 Answer

Steven Parker
Steven Parker
200,698 Points

:point_right: You can test for a negative number by comparing it with 0.

In the else that follows the except, you could do something like this:

    if (my_guess < 0):
        print("ERROR: The number must not be negative!")
        # Do the same thing here as you do after the exception print