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 trialsurenanand
1,203 PointsI have return code right and working in my machine. def squared(num): try:
Please review and let me know.
Treehouse console returning as error
# 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 * 2
else:
return num * num
3 Answers
Jennifer Nordell
Treehouse TeacherHi there Suren Visvaratnam! You're super close here. The problem is in the line that happens when it generates a ValueError
. A ValueError
will happen if we send in a string like "hi" that cannot be converted to an int. In that case, we want to multiply the string by the length of the string. So if we had a 4 letter word like "tree", it should print "tree" four times: treetreetreetree. Yours is always printing it exactly twice regardless of the length of the string.
So if I change this:
return num * 2
To this:
return num * len(num)
... your code passes! Hope this helps!
Hirenkumar Patel
Courses Plus Student 9,464 PointsHere is answer def squared(num): try: mynum = int(num)*int(num) return mynum except ValueError: print(num*len(num))
check
print(squared("tim"))
surenanand
1,203 PointsI am getting syntax error
surenanand
1,203 Pointssurenanand
1,203 PointsThanks...Now i understood.