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 trialFHATUWANI Dondry MUVHANGO
17,796 Pointsi am having trouble with the "try and except" question
what am i doing wrong?
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(num):
try:
num = int(num)
except ValueError:
return num*num
4 Answers
Jennifer Nordell
Treehouse TeacherHi there! You have a couple of things going on with your code. First, you are trying to convert num to an integer (which is good), but then you assign it back into num and never return anything. Assuming that num can be converted to an integer, we want to return the number times itself.
However, in the except clause you do return the number times itself. However it's here that we want to return the value of the variable times the length of the value. We've already determined that it's not an integer as that's already failed. Take a look:
def squared(num):
try:
return int(num) ** 2
except ValueError:
return num * len(num)
Here we define a function named squared
which takes a piece of information. We'd like that to be an integer and return the square of that integer. So we try and do just that. We try first to make the conversion to integer and the raise it to the second power. If that fails with a ValueError
it means that what we got in was not an integer and cannot be converted to an integer. In this case, we want to take the value and multiply it by the length of that value.
Hope this helps!
jacinator
11,936 Pointsdef squared(num):
try:
return int(num) ** 2 # Try to convert num to an int and return the square of num
except ValueError:
return num * len(num) # Otherwise return num by the length of num
FHATUWANI Dondry MUVHANGO
17,796 Pointsit did help. thank you
Burton King
3,938 PointsAnother example of poorly written code challenges. Really frustrated with this pattern.