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

Luis Miguel Hernandez
Luis Miguel Hernandez
4,266 Points

I dont understand!! I belive that my code works.. or no?

Help me, ok.. the code no it is the better but y think that is works!

squared.py
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"

def squared(number):
    try:
        number = int(number)
        res = number
        multi = number
    except ValueError:
        texto = list(number)
        res = texto
        multi = len(texto)

    res *= multi

    return res

1 Answer

Antonio De Rose
Antonio De Rose
20,885 Points

question

you've been asked to do only 2 things, with the use of try and except

problem 1 - if the argument is able to be converted into int, return the result of

which is either num * num or num * 2

problem 2 - if the argument is not able to be converted into a number, then

return the argument multiplied by it's length

def squared(number):
    try:
        return int(number) * int(number) # problem 1
    except ValueError:
        return len(number) * number # problem 2

your answer - try breaking down the question into parts, you have made it really complex which could have been solved easily, had you broken down the questions into use cases

def squared(number):
    try:
        number = int(number) #correct
        res = number #redundant
        multi = number #redudant
    except ValueError:
        texto = list(number) #why list no need
        res = texto #redundant
        multi = len(texto) #this leads to be wrong, when you have come using the list

    res *= multi #there should be 2 returns, if try works one from try else return from except

    return res