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

Arun Patel
Arun Patel
1,180 Points

Why the function didn't return right answer?

I executed same code separately and got right answer (25)

def squared(x): try: x = int(x) y = x * x return y except ValueError: x = str(x) z = x + x return z

def test(): x = squared(5) print(x)

test()

squared.py
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(x):
    try:
        x = int(x)
        y = x * x
        return y
    except ValueError:
        x = str(x)
        y = x + x
        return y
Anibal Marquina
Anibal Marquina
9,523 Points
# Check you Try block.
# If the argument (arg) can be turned into an integer then is a number... return the square value of that argument.
# If the argument (arg) cannot be turned into an integer.. then return the argument multiplied by its length.

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

1 Answer

Hello there,

You're close - the only thing not functioning correctly is when it passes a string value. With the way it works right now, using x + x, it will just print the string twice. However, it is supposed to print the string a number of times equal to the strings length, so it should instead be x * len(x). With that one line changed, it looks like this:

def squared(x):
    try:
        x = int(x)
        y = x * x
        return y
    except ValueError:
        x = str(x)
        y = x * len(x)
        return y

If you have things spaced out to make it easier to read as you're learning, that's totally fine. If you're interested, though, this can be shortened a good bit:

def squared(x):
    try:
        return int(x) * int(x)  #can also do int(x) ** 2  (exponent notation)
    except ValueError:
        return x * len(x)
Arun Patel
Arun Patel
1,180 Points

Thanks a lot for the clarification.