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 trialAli Dahud
3,459 PointsCould you break down this code for me? Step by step
Could you please?
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(item):
try:
return int((item) ** 2)
except:
length = len(item)
return item*length
2 Answers
Elgene Ee
3,554 PointsOh I see Ali, It is okay to get frustrated sometimes, but just make sure you practice... So we want integers to get squared, there are 2 ways to square them
- (item * item)
- (item ** 2) the int function is to ensure that the output is integer( let's say we type squared(4.3), the outcome will be 4 with the help of int function)
Now things get a bit tricky, is to multiply strings, but how... We need the len function to get number of words we have...(let's say 'hello' has 5 chars) --> return item * len(item) This function multiply the strings with the number of chars it has.
Hope that helps
Elgene Ee
3,554 PointsHi Ali, As you multiply a string(let's say "hi") with any integer(let's say 2), it will turn out to be --> ("hihi") Good job that at least you understand in try block! Keep it up
def squared(item):
try:
return int(item) ** 2
except:
return item * len(item)
Ali Dahud
3,459 PointsActually I donβt understand anything from it. :( I just copied someone elseβs code