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

I can't figure out what's wrong with my code. please help

def squared(num): while True: try: int(num) except ValueError: return(num*len(num)) else: return(num*num)

squared.py
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(num):
    while True:
        try:
            int(num)
        except ValueError:
            return(num*len(num))
        else:
            return(num*num)

1 Answer

Ioannis Leontiadis
Ioannis Leontiadis
9,828 Points

Hello,

when using int( String ) to a string that can be converted to an integer, i.e. "2", your try statement executes just fine but fails in the else clause when it tries to multiply the string by itself.

Try assigning the parsed string into a variable. That way if the parsing fails, the except clause will execute but if it does not you will have an integer to deal with.

For example try,

num = int( num )

Hope that helped!

Thank you!!