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

Mark Coup
Mark Coup
1,112 Points

Not sure how to structure this

I'm supposed to define squared(): then square the argument if it can be converted to an integer. If not multiply the argument by it's length.

I'm not sure if I should use a loop here? Or if I'm using int() correctly?

squared.py
# EXAMPLES
def squared(square_test):
    try:
        if int(square_test) == int():
            return squared(square_test)
    except: 
        if int(square_test) == ValueError:
            return squared(square_test)
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"

1 Answer

Steven Parker
Steven Parker
231,007 Points

Here's a few hints:

  • you won't need a loop
  • you won't want to call yourself (squared) inside your function (infinite loop!)
  • inside the try, convert the argument to integer and save it in a local variable
  • if your conversion is successful, return the converted number multiplied by itself
  • if your conversion is not successful, return the original argument multiplied by its length

I'll bet you can get it now.