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

Any advice for a beginner who has been trying a couple days?

I think its something i just don't understand.

squared.py
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(num):
    a = int(num)
    b = str(num)
    try:
        if num != int:
            return a * a
    except:
        return num * len(b)

2 Answers

AJ Salmon
AJ Salmon
5,675 Points

Hi Glen!

Don't get discouraged, you have the right idea. You know what you're supposed to do, but the goal here, or when writing any python code, really, is to do it as simply and efficiently as possible. Firstly, in try and except blocks, you need to tell the except what to catch. In this case, if num cannot be converted into an integer, it will raise a ValueError. So, in the try portion, pretend like num definitely can be turned into an integer with int(), because if it can't, the except portion will catch the error, and do whatever you tell it to do in the case of that ValueError.

def squared(num):
    try:
        #return num ** 2 after converting it into an integer.
        #you can do this in one line
    except ValueError:
        #if num can't be converted to int, return
        #num times the length of num
        #this can also be done on one line

You don't need to create variables for int(num) and str(num), because you'll try converting num into an integer inside the try portion. If you try converting it outside of the try and except block, however, it will raise the error without returning the desired object. You don't need any extra variables, just num and python's built-in functions. Hope this helps, and happy coding!

AJ

Steven Parker
Steven Parker
231,271 Points

Here's a few hints:

  • for the "except" to work on conversion errors, the conversions must be done inside the "try" block
  • you won't need to use "str" in this challenge (you only need to convert to int)
  • "int" is not a value you can compare against
  • you shouldn't need to perform any conditional tests