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 am not sure if I am using the return or len functions properly. Any advice would be great!

I am trying to use the len function to find the length of a string-I don't think I am doing it properly. I also am not sure about the return function.

def squared("example"):
      return(((len("example") ** len("example")))

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

2 Answers

Josh Keenan
Josh Keenan
19,652 Points

Slight mistake on the structure of it but don't worry, I will explain all.

Here's my solution.

def squared(num):
    return (int(num) ** 2)
  except ValueError:
    return (str(num) * len(num))

Firstly we create a new parameter that is not a string like in yours, it's like a variable in a way!

Then we are using try to convert it to an integer, so we place an attempt to convert to an integer in the try block:

int(num) # <-- this converts something to an integer

With this inside the try block we try to make it an integer. If this doesn't work then we catch the error and have a solution to handle the problem, which is the except block.

except ValueError:
    return (str(num) * len(num))

Then in the except block we return the parameter but convert it to a string if it isn't one already, then return it as many times as it is long.

Hope this helps!

Thank you!