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 Squared

Paul Heneghan
Paul Heneghan
14,380 Points

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

Thank you!

squared.py
# EXAMPLES
# 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)
        try:
            return(num **2)
        except:
            return(num * len(num))

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
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,380 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.