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!
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
Don't really know what's happening...
Don't really understand this code challenge... Please help!
# EXAMPLES def squared(game): try int(game): if int(game): return( game**2) except ValueError: return(game * len(game)) # squared(5) would return 25 # squared("2") would return 4 # squared("tim") would return "timtimtim"
Renato Guzman51,256 Points
The code looks almost okay.
First, the try-except block has some syntax errors.
The block should be like:
try: something... except ValueError: something...
So, the int conversion should be done inside try and not in the same line.
Then should try with the value "0". Since you are putting if int("0"), this will return False and the function will return None which is wrong.
It seems that you understood the challenge, but you just need a few tweaks.
Rich Zimmerman24,063 Points
So in your try block, you want to convert it to an int. If it's not able to conver to an int, it will throw an error and jump to the except block. If it's able to convert to an int (meaning it wont throw an exception), you want to return the argument ** 2, or argument * argument (i.e. 5 * 5 or 5 ** 2)
If it cannot convert to an int, you want to return the argument times the length of the argument, so if you do
It would return "timtimtim"
def squared(arg): try: return int(arg) ** 2 except ValueError: return arg * len(arg)