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

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!