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 trialSultan Abdullah
Full Stack JavaScript Techdegree Student 9,985 PointsSquare(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 ?
# 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)
4 Answers
Antonyo Hutsona
886 Pointsdef squared(num): try: return int(num) ** 2 except ValueError: return len(num) * num
Sultan Abdullah
Full Stack JavaScript Techdegree Student 9,985 PointsThanks, that worked!
I still dont know why though xD
Igor Lukin
1,689 Pointsfor 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?
Sultan Abdullah
Full Stack JavaScript Techdegree Student 9,985 PointsI see, thanks!
Antonyo Hutsona
886 PointsI think it's because you didn't name the exception you were trying to throw...
except ValueError:
Sultan Abdullah
Full Stack JavaScript Techdegree Student 9,985 PointsI checked that, It says " TypeError: Can't multiply sequence by non-int type 'str' "
Sultan Abdullah
Full Stack JavaScript Techdegree Student 9,985 PointsI 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..
Antonyo Hutsona
886 PointsAntonyo Hutsona
886 Pointsdef squared(num): try: return int(num) ** 2 except ValueError: return len(num) * num