Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics (2015) Number Game App Squared

Paul Heneghan
Paul Heneghan
14,337 Points

Tried this as a if/else, and it works, but I'm missing something when I use try/except.

Thank you!

# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"

def squared(num):
    if type(num) != int:
        num = int(num)
            return(num **2)
            return(num * len(num))

1 Answer

Jennifer Nordell
Jennifer Nordell
Treehouse Teacher

Hi there! You're so close here! And because you're so close, I'm going to see if you can get the solution with a few hints. First, you can remove the if part altogether. All you'll need here is a try and except. And what exactly are we trying? We're trying to convert the input into an int. You need to be testing first if the number can be turned into an int and then squared and return that result. However, if it fails, it should go to the except ValueError block, where your code is currently correct :smiley: Hope this helps! :sparkles:

Paul Heneghan
Paul Heneghan
14,337 Points

Jennifer, you're the best! You weren't kidding, I was right there already, except I stacked the if above the plain old "try". Probably because I started out that way, and am more used to if/else in exercises so far, I just added more layers than I needed. Lesson learned. Thanks for you help and thanks for the rapid response.