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 trial

Python Python Basics (2015) Number Game App Squared

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!

squared.py
# 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)

1 Answer

Henrik Christensen
seal-mask
.a{fill-rule:evenodd;}techdegree
Henrik Christensen
Python 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