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

Enzie Riddle
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Enzie Riddle
Front End Web Development Techdegree Graduate 19,278 Points

Integer

I fairly lost on this challenge. Here's the question:

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.

What am I doing wrong?

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

Using the example of "tim" becoming "timtimtim", that is a replication, i.e. "tim"*3

2 Answers

so its asking you to tell if a number going INTO a function is either a int (or into convertible) or a something else if its not an int they want you to return it multiplied by its length

the examples really are key here, if I call the function like this

number = squared("2") I would expect the value of number to be 4

so in my little example I handed you a string with a value of 2, but since it convertible your function needs to convert it

If I hand you

number = squared("2f")

I would expect the following: number = "2f2f"

you want to try and except inside the function. I wont solve if for you but it should be something like this logically

def squared(number):
#try int number?
return square of that number
#except
return string * length of string

If you remember strings in python can be multiplied so a string with a value of "HI" * 5 would get you HIHIHIHIHI

TLDR: Your try except is outside the function, and as such your function is not responding as expected

You might review what you were supposed to return in the case of an error.