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 trialB.B Eight
725 PointsI can't figure out what's wrong with my code. please help
def squared(num): while True: try: int(num) except ValueError: return(num*len(num)) else: return(num*num)
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(num):
while True:
try:
int(num)
except ValueError:
return(num*len(num))
else:
return(num*num)
1 Answer
Ioannis Leontiadis
9,828 PointsHello,
when using int( String ) to a string that can be converted to an integer, i.e. "2", your try statement executes just fine but fails in the else clause when it tries to multiply the string by itself.
Try assigning the parsed string into a variable. That way if the parsing fails, the except clause will execute but if it does not you will have an integer to deal with.
For example try,
num = int( num )
Hope that helped!
B.B Eight
725 PointsB.B Eight
725 PointsThank you!!