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

Grace Baecher
Grace Baecher
578 Points

This challenge is similar to an earlier one. Remember, though, I want you to practice! You'll probably want to use try a

can someone please tell me the correct answer. I've tried to fix it a million time.

squared.py
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
Grace Baecher
Grace Baecher
578 Points
def squared(x):
    try:
        if x == int(x):
            return (x**2)
    except:
        return (x*len(x))

1 Answer

AJ Salmon
AJ Salmon
5,675 Points

Hey Grace! This one can be tricky. Here's how I completed it:

First, create the function and set the parameters, like you did. Then we can write our try and except block.

def squared(x):
    try:

In the try portion, we're supposed to return the square of the input, but only if it can be converted into an integer. We're just telling it to try to return int(x) * int(x).

def squared(x):
    try:
        return int(x)**2

Then, in the except portion, we tell it to catch a ValueError. This is the error that pops up when x can't be converted into an integer. When this happens, we're supposed to return the argument multiplied by its length.

def squared(x):
    try:
        return int(x)**2
    except ValueError:
        return len(x) * x