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 trialManasa Gurrala
710 PointsSquared
How to obtain the argument of a string and what mistake am i making here
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(a):
try:
int(a) == True
return (a * a)
except ValueError:
return float(a) * len(a)
2 Answers
Manasa Gurrala
710 PointsThanks it worked
Umar A
4,041 PointsHi Manasa Gurrala, try this code:
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(a):
try:
a = int(a) # this is how to convert a string into an int
a = a * a # once you have an int, you multiply it by itself
except ValueError:
a = a * len(a) # if the input is not an int ( e.g a string ), you multiply it by its length using the len method then store it again in the variable a
return a # last thing, the squared function will return the variable a as an output
Umar A
4,041 PointsUmar A
4,041 PointsYou're welcome :)