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!
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 trial
Sirui Ma1,371 Points
Squared function cannot return correct values for "2"
Hi, I wrote the code as below, but i cannot get correct values. If you enter 5, it can give you 25, but if you enter "5", it will only give you "5""5""5". Anyone know the reason? Thanks!
# EXAMPLES # squared(5) would return 25 # squared("2") would return 4 # squared("tim") would return "timtimtim" def squared(letter): try: num=int(letter) except ValueError: letter*len(letter) else: int(letter)*int(letter)
Henrik ChristensenPython Web Development Techdegree Student 38,322 Points
You are told to return the value in the except block and the value in the else block.
# EXAMPLES # squared(5) would return 25 # squared("2") would return 4 # squared("tim") would return "timtimtim" def squared(x): try: num = int(x) except ValueError: return x * len(x) # notice the return else: # here I don't understand why you are doing (just a tip): # int(letter) * int(letter) when you already have int(letter) stored in the num variable return num * num # notice the return