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 trialwillyraider
6,550 PointsWrite a function named squared that takes a single argument (Python Basics Track)
I don't know what's wrong with this code but I'm getting always a bummer! Although the output is the same as requested. Could someone please review this?
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(value):
try:
return print(int(value) ** 2)
except TypeError:
return print(value*3)
except ValueError:
return print('"'+value*3+'"')
squared(5)
squared("2")
squared("tim")
I've also tried for the ValueError part
return print(value*3)
but doesn't work as well.
Really frustrating :-(
1 Answer
Josh Keenan
20,315 PointsHere's my solution
def squared(num):
try:
return (int(num) ** 2)
except ValueError:
return (str(num) * len(num))
You don't want it to print
so that isn't needed.
You want to catch a ValueError
You need an else
to return the other alternative if conversion fails
willyraider
6,550 Pointswillyraider
6,550 PointsIt worked out! Thank you Josh Keenan!
Josh Keenan
20,315 PointsJosh Keenan
20,315 PointsHappy to help! :)
John Mills
Python Web Development Techdegree Student 565 PointsJohn Mills
Python Web Development Techdegree Student 565 PointsGreat work Josh, but remember you don't have to use parenthesis around your return values, the entire line gets returned automatically. Also, I recommend you use 4 spaces, rather than 2. 4 spaces reads better and is a Python standard. Happy coding!
Josh Keenan
20,315 PointsJosh Keenan
20,315 PointsI prefer it for readability as do my lecturers, the grades come first xD
edit: I do use 4 but when I copy in it never works and loses all indentation and typing 2 spaces is easier than 4