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 trialBeth Singley
3,491 PointsI don't understand why my squared function is not working
In my brain, the code below should work. I cannot find a good reason why it doesn't. What am I missing?
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared (num):
try:
test = int(num)
return (test ** 2)
except TypeError:
return (num * len(num))
2 Answers
Anish Walawalkar
8,534 PointsJust change TypeError to ValueError. when python encounters a string it cannot convert to an int/double it throws a ValueError
Florin Veja
6,912 PointsBeth,
It looks like the squared("tim") is what is failing. The error you are getting is "ValueError: invalid literal for int() with base 10: 'tim'". I believe you might need to change the "except TypeError:" line to "except ValueError:"
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared (num):
try:
test = int(num)
return (test ** 2)
except ValueError:
return (num * len(num))
Let me know if that helps.
Cheers,
Florin