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

How do I write under function block "If argument can be converted to integer"?

Hi guys. I'm currently stuck with squared code challenge. How do I write "if arguments can be converted to integer"?

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

1 Answer

Hi Mohd

The task wants you to try to convert the passed in argument i.e numbers to an integer, if it succeeds then return the result of multiplying the argument(numbers) by itself. If it does not succeed then return the argument(numbers) multiplied by its length, assuming its a string.

see below

def squared(numbers):
  try:
    numbers = int(numbers)
    return (numbers ** 2)
  except:
    return numbers * len(numbers)