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

KARTIK BHASIN
KARTIK BHASIN
9,299 Points

Can't Understand my error

We can directly multiply string with an int. Then what is the problem?

squared.py
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(num):
    try:
        num2=int(num)
    except ValueError:
        num3=len(num)
        return (num*num3)
    else:
        return (num*num)

2 Answers

Gavin Ralston
Gavin Ralston
28,770 Points

Here's one way to do it.

Once you've failed to convert a string to an int, you know you're dealing with an alphanumeric string. Otherwise, there's no harm in casting an int to an int in the try block, and it'll handle all the strings that can be converted to an integer.

def squared(num):
    try:
        return int(num) ** 2
    except ValueError:
        return num * len(num)

The way you did it is fine, too. The one gotcha, though, is that you never do anything with that num2 variable! If you successfully cast a string to an integer in num2, you didn't do anything with it.

This is one way you could change your original code to make it work, and you get rid of the unnecessary else block:

def squared(num):
    try:
        num2=int(num)
        return num2 ** 2
    except ValueError:
        num3=len(num)
        return (num*num3)
Avani Agrawal
Avani Agrawal
1,638 Points

This worked for me -

def squared(num):
    try:
        num2=int(num)
        return num2**2
    except ValueError:
        length=len(num)
        return (num*length)

Firstly, from your code, I feel the return statement should be in the try block which will return the integer value, if the parsing is done right. If not, we raise a ValueError when the input is not an integer and it fails parsing to int in the 'try' block and the corresponding code is in the 'except' block. If you have happen to Java, it is the same logic as a try-catch. Hope this helps!