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

Sam Bui
Sam Bui
878 Points

get stuck at squared.py challenge

Hi, I am doing this challenge, this is what it ask:

Use try and except on this one. You might have to not use the else block. 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.

I have try several methods but nothing works and i don't really know what wrong with my code, if you could show me, that would be great.

Thank

squared.py
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"

def squared(num):
    num = input('> ')
    try:
        square = int(num)
        return square ** 2
    except ValueError:
        return num * len(num)

1 Answer

You did great!

:point_right: But why are you capturing user input? The challenge didn't ask for that.

Just remove this line:

num = input('> ')

And your code passes :smiley:

I hope this helps :grin:

:dizzy: ~Alex :dizzy:

Sam Bui
Sam Bui
878 Points

Hi Alexander, thank you for your help, it works just like you say :) At first I thought I need an input function to get arguments and totally forget I can do that with squared(num): :| now when I look back, It make perfectly sense. I don't what I was thinking back then LOL :D