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 trialChristopher Kell
3,499 PointsSquared challenge
I keep getting a TypeError: can't multiply sequence by non-int of type 'str'. do I have to make a variable to fix this problem?
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(x):
try:
return int(x*x)
except ValueError:
return str(x)*len(str(x))
1 Answer
Alexander Davison
65,469 PointsYou have done every well! It took me a while to find out the error. You must actually change x to ints separately.
Also, you don't have to do this but it's usually cleaner to not change the value to a type if you know it's going to be that type. That means to make your code cleaner you should get rid of the str() function calls completely (remember you don't have to do that it just makes the code cleaner )
Try this:
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(x):
try:
return int(x) * int(x)
except ValueError:
return x * len(x)
Good luck! ~Alex
Christopher Kell
3,499 PointsChristopher Kell
3,499 PointsThat worked very well thank you! Great advise also.
Alexander Davison
65,469 PointsAlexander Davison
65,469 PointsNo problem :)