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 trialLatoshia Wheeler
Courses Plus Student 778 Pointssquared.py
I looked at the answers others got to this one and i really don't understand where I went wrong. I tried it in the workspace as a print out to see why my error message keeps saying the return isn't correct but I cant see it. if the len of the string is 5 and we do 5 squared it is twenty five and that's what it prints out but that isn't what it returns. So I am confused!!!!
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(one):
try:
one = int(one)
except ValueError:
return (len(one) **2)
squared("three")
3 Answers
Kenneth Love
Treehouse Guest TeacherYou have three conditions you need to solve in this challenge.
- If
squared()
gets a number as the argument, you should square that number (squared(5)
returns 25) - If
squared()
gets a number inside a string as the argument, you need to convert it to a number and then square it (squared("2")
returns 4) - And, finally, if
squared()
gets a non-numeric string, you need to return that string multiplied by its length (squared("three")
returns "threethreethreethreethree")
Right now, your code doesn't address any of these scenarios, though. Right now, your code tries to convert the input into an integer and, if that fails, returns the square of the length of the string. So squared("three")
would return 25 instead of the, above, correct answer.
Try to solve them one at a time. How would you approach the first one?
Latoshia Wheeler
Courses Plus Student 778 Pointseach of the following work in workspaces but it's not working in the challenge so am I supposed to find a way for the code to do all three not just each individually? def squared(num): return len(num)*num
squared("three") # prints out "threethreethreethreethree"
def squared(num): return len(num)*num
squared(5) # this prints out 25
def squared2(num): try: int("num") except ValueError: return int(num) * 2 squared(2) # this prints out 4
so what am I doing wrong?
Kenneth Love
Treehouse Guest TeacherYeah, your code will need to do all three. Also int("num")
is never going to work as the string "num"
isn't a number value.
Latoshia Wheeler
Courses Plus Student 778 PointsOk gotcha hopefully i understand now thx for all the help