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

square of a number

This challenge is similar to an earlier one. Remember, though, I want you to practice! You'll probably want to use try and except on this one. You might have to not use the else block, though.

Write a function named squared that takes a single argument.

If the argument can be converted into an integer, convert it and return the square of the number (num ** 2 or num * num).

If the argument cannot be turned into an integer (maybe it's a string of non-numbers?), return the argument multiplied by its length. Look in the file for examples.

Above is the challenge, could not get the right answer please help me out,

Thank you

squared.py
# EXAMPLES
# squared(5) would return 25
def squared(num):
    try:
        int(num)
    except valueError:
        print("thats not a number")
    else:
        print(num**2)
#    if num = int(number):
#        return(num**2)
#    else:
#        print(num**2)
# squared("2") would return 4
# squared("tim") would return "timtimtim"

1 Answer

Dave Harker
PLUS
Dave Harker
Courses Plus Student 15,510 Points

Hi CH. K Sri Krishna,

# Write a function named squared that takes a single argument.
def squared(num): # done, good.

# If the argument can be converted into an integer, convert it and
# return the square of the number (num ** 2 or num * num).
    try:

        # it's good you're testing it here, but why not just return here too?
        # perhaps try returning (int)num ** 2 directly here
        int(num) 

    # we don't care at this point why type of exception is thrown, just that it is. But either way :)
    except ValueError: 

        # if it failed casting it means we're here and it's not a number 
        # so let's just return num * len(num) at this point, then we don't need an else
        print("thats not a number") #return here instead of print

    # an else isn't necessary anymore because the requirements are met and
    # all scenarions are dealt with already :)
    else:
        print(num**2)

Thought I'd just put the reasoning in comments.
You're almost there, keep going :smile:

Hope that helps :dizzy:
Dave