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

Idan shami
Idan shami
13,251 Points

how to solve this challenge? help, please...

please help. I don't understand what I need to do here.... also, can you remind me videos that will help me solve it, why do I need to use try: and except here? Thanks, Idan.

squared.py
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(num):
    if number == num:
        return int(num) ** 2
    elif string == num:
        return string * len(string)

1 Answer

Steven Parker
Steven Parker
230,230 Points

You haven't defined any variables named "number" or "string".

I'm guessing you were trying to determine the type of the argument, but that's not a way to do it. But you don't need to anyway, that's the whole point of try and except. If you try to convert the argument into an integer within a try, it will either succeed (and then you can deal with the number) or go to the except where you can then deal with it as something else.

Idan shami
Idan shami
13,251 Points

I'm sorry.... I still cannot solve it.... here is my code

def squared(num):
    try:
        return int(num ** 2)
    except ValueError:
        return (num * len(num))
Steven Parker
Steven Parker
230,230 Points

You are really close now!
But you can't square the input before you convert it to a number. So really your only issue now is that closing parenthesis is in the wrong place.

Idan shami
Idan shami
13,251 Points

Thanks it worked, I will remember it for the future! it is possible with if statement though? if it is so how?

Steven Parker
Steven Parker
230,230 Points

It wouldn't be easy to do this another way, because you can't assume the passed argument is an integer number to start with. It could just be a string. Your objective is to see if it can be converted to an integer.