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 trialMohd Faiz Bin Abdul Jalil
509 PointsHow 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"?
# 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
Andreas cormack
Python Web Development Techdegree Graduate 33,011 PointsHi 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)