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

Jimmy Holway
Jimmy Holway
10,703 Points

I get TypeError when running the attached code in the "Squared" code challege console but the desired result when runnin

I get:

Bummer! TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

when I run the below code but it's working for me in Terminal.

squared.py
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(n):
    val = ''
    try:
        if int(n):
            return n ** 2
    except ValueError:
            for i in n:
                val += n
            return val

3 Answers

Kourosh Raeen
Kourosh Raeen
23,733 Points

There is no need for an if statement. In the try block just convert to an int then square it. In the except block multiply n by it's length per instructions, so no need for a loop there:

# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(n):
  try:
    return int(n) ** 2
  except ValueError:
    return n * len(n)
Steven Parker
Steven Parker
231,248 Points

I'm assuming you'd rather have some hints instead of an outright spoiler.

A couple of issues I noticed:

  • if your function is given 0 (zero), it returns nothing ("None") instead of 0.
  • if your function is given a number as a string (like "2") it tries to square the string itself

Also, while it may not affect passing the challenge, there's a much simpler way to create a repeated string.

Jimmy Holway
Jimmy Holway
10,703 Points

Thanks! I could see that Kourosh's answer was better than mine but your comment made me understand why.

Jimmy Holway
Jimmy Holway
10,703 Points

Thanks Kourosh! Not great at boiling this stuff down to it's simplest state yet.

Steven Parker
Steven Parker
231,248 Points

Perhaps you did prefer a spoiler. :disappointed: