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) Logic in Python Try and Except

Ranko Milic
PLUS
Ranko Milic
Courses Plus Student 1,768 Points

what's wrong with the try challenge?

What's wrong with this piece of code for the try challenge where I should try to catch Value Error and return None if n1 and n2 are not numbers and if they are numbers, they are turned into floats and returned as a sum of both floats?

def add(n1, n2):
  try:
    except ValueError:
    return None
  else:
    n1=float(n1)
    n2=float(n2)
    return n1+n2   
add(3,5)

Thanks...

rydavim
rydavim
18,814 Points

I've added some code formatting to your post. You can do this using the following markdown:

```language

your code here

```

5 Answers

George S-T
George S-T
6,624 Points

Hi Ranko.

Ive had a look at the challenge, this code passed for me:

def add(arg, arg_2):
  try:
    floats = float(arg) + float(arg_2)
  except ValueError:
    return None
  else:
    return floats

Your try block should be attempting to add together the floats. If there is an error, nothing is returned. If there is no error (else), then the floats are returned.

Hope this helps

George S-T
George S-T
6,624 Points

Hi, please try to re-format your code in the question using three backticks so it's easier for us to see and help you.

Brifely looking, you don't seem to have anything after try: ?

try: You do your operations here; ......................

except: If there is any exception, then execute this block. ......................

else: If there is no exception then execute this block.

Ranko Milic
PLUS
Ranko Milic
Courses Plus Student 1,768 Points

Thanks, George...

I have problem with "do your operations here" because there seem to be no any operations other than these two. Namely, the story goes: before turning numbers into floats and returning them as sum, check if there is any value error and if there is, return None...

What do you suggest?

Thanks again!

Ranko Milic
PLUS
Ranko Milic
Courses Plus Student 1,768 Points

Thanks, Rydavim, as well... I will try formatting next time I post the question...