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

Ayaz Alam
Ayaz Alam
564 Points

TypeError: can't multiply sequence by non-int of type 'str'

I can multiply by num * len(num) in python shell but still i am getting this error : TypeError: can't multiply sequence by non-int of type 'str'

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

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

2 Answers

Samuel Ferree
Samuel Ferree
31,722 Points

the int function returns a new value, it doesn't change the value of the variable passed in. In order to set num to the int type using the int function, you need to assign num, to the value that the int function returns.

Like so:

# ...
try:
  num = int(num)
except ValueError:
# ...
james south
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
james south
Front End Web Development Techdegree Graduate 33,271 Points

your code is fine you just need to tweak your try block a little. int(num) isn't re-setting num as an int. for that you just need to re-assign to num an int cast of itself. then the code will pass.