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

Rakesh Bharadwaj
Rakesh Bharadwaj
1,376 Points

My answer when executed gives output properly but it is giving error here

EXAMPLES

squared(5) would return 25

def squared(num1): try: num1=int(num1 ** 2)

except TypeError:
    return(len(num1) * num1)

squared("2") would return 4

squared("tim") would return "timtimtim"

squared.py
# EXAMPLES
# squared(5) would return 25
def squared(num1):
    try:
        num1=int(num1 ** 2)

    except TypeError:
        return(len(num1) * num1)
# squared("2") would return 4
# squared("tim") would return "timtimtim"

1 Answer

Stuart Wright
Stuart Wright
41,120 Points

There are a few issues with your solution. Note that int(num1 ** 2) is different than int(num1) ** 2. The former squares num1 then converts to integer. The latter converts num1 to integer then squares it. These give different results if num1 is a float such as 3.5. It's important to read the instructions carefully in these challenges to make sure you're doing exactly what it asks you.

Another issue is that in the case where you are able to square the number, you are not returning anything.

Finally, if you are unable to convert the input to an integer, it will actually result in a ValueError rather than a TypeError, although I believe the challenge will also accept a generic 'except:' to catch all exceptions.

A full solution might look like this:

def squared(num1):
    try:
        square = int(num1) ** 2
        return square
    except ValueError:
        return len(num1) * num1