Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics (2015) Number Game App Squared

Arthur Berg
Arthur Berg
11,350 Points

try, except, else

I can't see what's wrong with my code? I'm checking if the argument is an int with type(num) == int. Is this the wrong way to do it?

Appreciate any help!

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

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

4 Answers

def squared(num):
  try:
    int(num)
  except ValueError:
    return num * len(num)
  else:
    return int(num) ** 2 
// or     return int(num) * int(num)
Arthur Berg
Arthur Berg
11,350 Points

ahh I forgot to convert it , obvs... my type(num) == int syntax works like int(num) in the try block?

Well let me show you on IDLE:

>>> int("1")
1
>>> int("test")

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    int("test")
ValueError: invalid literal for int() with base 10: 'test'
>>> 
>>> num = "test"
>>> type(num) == int
False
>>> 

You get the difference ;)?

type() returns True or False while int() returns an integer (string converted to an int) or (what we need) an error-message

dont copy my comment Just to show you some other ways

// or     return int(num) * int(num)
Arthur Berg
Arthur Berg
11,350 Points

I get it, thanks Tobias! New to Python, learning it in order to build shopping system with stripe and django. Coming from beginner/intermediate level of Javascript, mostly angular!