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

Square(int) function with "try""except" works in workspace, but wont pass the code challenge ?!

This code challenge is asking me to make function with 1 argument. and this should happen: 1) if its an integer, return it squared 2) if not (a string) then multiply that string with its length

This is the code I ran and im getting " 'squared' didn't return the correct results ". I checked the code on workspace using the examples at the top of the code and it works as intended. Am I missing something here ?

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

def squared(arg):
    try:
        int(arg)
        return arg*arg
    except:
        return arg*len(arg)
Antonyo Hutsona
Antonyo Hutsona
886 Points

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

4 Answers

Antonyo Hutsona
Antonyo Hutsona
886 Points

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

Thanks, that worked!

I still dont know why though xD

Igor Lukin
Igor Lukin
1,689 Points

for example you wrote in arg '5'. It could be int('5'), right? But you can't multiply that string '5'*'5', because you didn't save the restult in arg variable. But you can first to int it and then mulptiply that, ok?

I see, thanks!

Antonyo Hutsona
Antonyo Hutsona
886 Points

I think it's because you didn't name the exception you were trying to throw...

except ValueError:

I checked that, It says " TypeError: Can't multiply sequence by non-int type 'str' "

I see, In your code, the int() is embedded in the return. I editted my code from:

" int(arg) return arg**2"

to

" return int(arg)**2"

And it got solved. Interesting..