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

gaetano amoroso
gaetano amoroso
2,993 Points

strange problem with a small python code

""" python snipet

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

""" in my local envoirment for python it works fine but in TREEHOUSE envoirment it retrieves back a TypeError: can't multiply sequence by non-int of type str.

that why ?

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)
  return num * num

1 Answer

Tobias Helmrich
Tobias Helmrich
31,603 Points

Hey Gaetano,

good job, you almost got it right! The only problem in your code is that you're not overwriting the num variable when you make it an integer. The int function doesn't overwrite the value, it just returns it and in this case you're multiplying a string by a string in the end which doesn't work. If you overwrite it, it should look like this and work:

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

I hope that helps! :)

gaetano amoroso
gaetano amoroso
2,993 Points

of course,you have helped me. it is very very great answer

Just num = int(num ) in try block