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 trialGlass Blade
3,677 PointsI need some help
I am a beginner to Python, and I am not sure what is wrong with my code. Can someonen please help me.
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(argument):
try:
if int(argument):
return int(argument ** 2)
except TypeError:
if True:
return argument * len(argument)
else:
if int(argument):
return int(argument ** 2)
2 Answers
Jennifer Nordell
Treehouse TeacherHi there! You're doing fine and hang in there. Here are some problems. You have if else statements you don't need. Particularly the else statement at the bottom. Here you're saying to take the argument to the power of 2 and try to make that an int and then return it. But we already know that it failed, because it wouldn't have gotten to the except block otherwise.
What you want to do is try to make the argument an int before you perform any other operations on it. Also your except block doesn't need to specify what kind of error. We want it work generically for any exception that comes up.
Spoiler alert! -- Here's how I did it:
def squared(argument):
try:
return int(argument) ** 2
except:
return argument * len(argument)
Hope this helps!
Alexander Davison
65,469 PointsJennifer Nordell did a good explanation about the problem