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

Paul Je
Paul Je
4,435 Points

Which part did I mess up?

Looked at another discussion on this challenge and there seemed no clear answer to this 3rd part of the problem. Looks like I combined the right parts of some of the answers there but still the try again message pops up. Can anybody help? Thank you!

trial.py
def add(x, y):
try: 
    a = float(x)
    b = float(y)
except ValueError:
    return None
  else:
    return a + b

3 Answers

Cheo R
Cheo R
37,150 Points

Hello Paul, you're on the right track, just need to make sure you're indentations are correct:

def add(x, y):
    try: 
        a = float(x)
        b = float(y)
    except ValueError:
        return None
    else:
        return a + b
Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there Paul Je ! We want to try to return the addition of the conversion of x and y, but if it fails then we return None. Cheo R posted a nice answer, but this one is a little shorter. Take a look:

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

Here we have a method named "add". It receives two pieces of input. We try and convert each one of them to a float separately. If either one fails to convert to a float, a ValueErrorwill be encountered at which point None is returned. Hope this helps! :sparkles:

Paul Je
Paul Je
4,435 Points

Great answers guys, helped me understand it a lot better. Thank you!!