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

Am I supposed to test for a string?

I think I have everything up to the except correct, but I'm not sure about testing for a string.

squared.py
def squared(num):
    try:
        return(num **2)
    except:
        return(len(num)*num)
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"

Hi Dan,

You've managed to return the correct value when squared takes an integer or a string which cannot be converted to an integer. However, you need to add the possibility for an integer wrapped inside a string (such as "2") to be converted to an integer. Currently, the program will fail the second test ( squared("2") ).

You can do the conversion with the int() function, which can take an argument of type string. If the string can be converted, it will not throw an exception, and if it cannot be converted, it will throw an exception. Thus, you can perform the conversion within try:

Below is not the code for completing the assignment but for testing this in Workspaces. You can complete the assignment by changing the print functions to return functions.

# function squared takes any value
def squared(num):

    # try to convert num to int
    try:
        num = int(num)

    # if conversion throws an exception
    except:
        print(num * len(num))

    # else (if try does not throw an exception)
    else:
        print(num ** 2)

squared(5)
squared("2")
squared("tim")