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

Squaring function won't return correct answer

I have tried various minor adjustments to this code, using ValueError and TypeError in the except block and defining a ret variable to pass the return values to. I've tried using the isinstance method to check if num is of type int and also the type(int) method but I don't seem to be getting anywhere. I know it'll be something simple that I'm missing. Any ideas?

squared.py
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(num):
    try:
        if type(num) is int:
            return num * num
    except TypeError:
        return num * len(num)

2 Answers

You are pretty close. You just need to make a couple changes.

def squared(arg):
    try:
        arg = int(arg) #< this line determines if the variable is a number or integer
    except ValueError:
        return arg * len(arg)
    else:
        return arg ** 2

Why doesn't this work?

def squared(num):
    try:
        return int(num) * int(num) #<-- Doesn't this check to see if "num" is a integer too?
    except ValueError:
        print(len(num) * num)
def squared(num):
    try:
        return int(num) * int(num)
    except ValueError:
        return len(num) * num

This works... it's cause I was printing and not returning the non integer value