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

don't quite have a handle on Try

I'm not sure I understand Try in the context of this question...i think this could be accomplished in a very simple manner with an If loop (?)

please help me understand how this all fits together.

squared.py
def squared(num):
    try:
        int(num)
        return(num * num)
    except ValueError:
        str(num)
        return(num * len(num))

squared("12")

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

1 Answer

Steven Parker
Steven Parker
231,236 Points

Calling "int(num)" allows the "try" to check if there are any errors in converting, but it does not store the converted value anywhere. But if you were to save the result ("num = int(num)"), then you could be sure you were multiplying numbers in the next step.

Another approach would be to just convert and multiply at the same time in the "return" statement.

thanks Steven. I think I understand " But if you were to save the result ("num = int(num)"), then you could be sure you were multiplying numbers in the next step." So, after a few configurations of trying to store the converted value, I have this which doesn't work either:

def squared(num): try: num == int(num) return(num * num) except ValueError: return(num * len(num))

I get the message: TypeError: can't multiply sequence by non-int of type 'str'

so I'm still a little stumped.

Steven Parker
Steven Parker
231,236 Points

It's hard to read unformatted Python, but I see a "==" (comparison operator) where I expected a "=" (assignment operator). This would mean the conversion result still wasn't saved.