Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics (2015) Number Game App Squared

Daniel Glennie
Daniel Glennie
42,854 Points

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

Russell Sawyer
seal-mask
.a{fill-rule:evenodd;}techdegree
Russell Sawyer
Front End Web Development Techdegree Student 15,705 Points

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
Patrick Liu
seal-mask
.a{fill-rule:evenodd;}techdegree
Patrick Liu
Full Stack JavaScript Techdegree Student 1,655 Points

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)
Patrick Liu
seal-mask
.a{fill-rule:evenodd;}techdegree
Patrick Liu
Full Stack JavaScript Techdegree Student 1,655 Points
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