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

Brett Vandyke
Brett Vandyke
4,981 Points

On the Squared code challenge. I'm having an issue getting the string conversion to work.

*Solved by OP *

I've tried a few workarounds, but I can't get the strings to convert. What am i missing?

squared.py
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
Brett Vandyke
Brett Vandyke
4,981 Points

I've been working in the workspaces instead of the challenge area. I forgot to paste the code over.

Here is the code:

def squared(x):
    try: 
        global var
        var = int(x)
        print (var ** 2)

    except ValueError:
        print("Input not a number.")
        var = int(var)
        print(var ** 2)

    except ValueError:
        print("Conversion failed. Multiplying string.")
        str_len = len(var)
        print( var * str_len )

In the original piece, I added a while loop for testing purposes . I decided to leave it out of the comment for clarity.

1 Answer

Brett Vandyke
Brett Vandyke
4,981 Points

I figured this one out. It dawned on me that I could use the function's argument instead of trying to fight through the variable scope issues.

def squared(x):
    try: 
        var = int(x)
        return(var ** 2)

    except ValueError:
        print("Not an integer.")
        length = len(x)
        string = x * length
        return string