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

Stuck With task 3 of 3(try and except)

Code Challenge task 3 of 3(Try and Except)

3 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

What does your code look like? It's hard to help you if I don't know exactly where you're stuck. :D

I had the same issue. I think I understand the syntax and logic of the "try" and "except" in Python, I just can't get them put into the challenge task 3/3 the way the program wants them, this is what I wrote: ( I copied the challenge text above)

You're doing great! Just one more task but it's a bigger one.

Right now, we turn everything into a float. That's great so long as we're getting numbers or numbers as a string. We should handle cases where we get a non-number, though.

Add a try block before where you turn your arguments into floats.

Then add an except to catch the possible ValueError. Inside the except block, return None.

If you're following the structure from the videos, add an else: for your final return of the added floats.

def add(x,y):
try:    
    float(x) + float(y)
except ValueError:
    return None
else:
    return float(x) + float(y)

Perhaps I have been at this for too long and can't see a simple error staring me in the face! Super frustrating!

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

It looks like you have some indentation errors? Everything should be indented inside of def add(x, y):.

Thanks for the quick reply. I gave it another go and indented everything below the "def add(x , y): " and it still gives an error. At this point it is rage over a lost penny (maybe not that mad, but still). This is what my last attempt looks like:

def add(x,y): try: float(x) + float(y) except ValueError return None else: return float(x) + float(y)

Teamtreehouse is kind of like Pokemon, you gotta catch em all !

So after typing in the whole code again (about 5 times) it just worked all of a sudden. This is the final code that worked:

def add(num1, num2): try: return float(num1) + float(num2) except ValueError: return(None) else: return float(num1) + float(num2)

The only thing I can see that is different is the parenthesis around the "None" in the except clause. scratches head