Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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:
try:
    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
else:

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

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

1 Answer

Steven Parker
Steven Parker
231,236 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