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 trialPete P
7,613 PointsAm I using 'try / except' correctly here?
The code works. But, for some reason I don't feel like this is the best way. Maybe the 2 returns look weird to me. Or maybe, the 'else' is not needed?
Is there a better way?
Thanks for all the help!
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(arg):
try:
arg = int(arg) ** 2
except:
return arg * len(arg)
else:
return arg
2 Answers
Cena Mayo
55,236 PointsHi Pete,
You wouldn't really use a try/expect loop this way. It's specifically intended to catch and return information about errors (otherwise known as 'exception handling').
So, to use your example, if your try statement doesn't work (which is wouldn't if arg is a string), then the except should be something like:
except:
print '{} is not an integer'.format(arg)
NOT, okay, well, try to process the arg this other way. Take a look here for a good brief overview of try/except.
Best, Cena
Steven Parker
231,269 PointsYou already know that your code passes the challenge just as is. This challenge is not asking for anything to be printed out, or any kind of error indication.
You are correct that the else is not needed, since in the first case the function would have already returned.