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

can someone tell me what im missing here? Am i putting the floats in the right place?

I have a feeling that that im putting the floats in the wrong block. Or are they supposed to be in both the the try and else block. Or am i just writing the code wrong?

trial.py
try:
    def add(num1, num2):
except ValueError:
        return(None)
else:
    return(float(num1) + float(num2))
add(5, 7)

1 Answer

A couple of things:

Your try block should be inside the function, but here you're defining the function within the try block.
Inside your try block, you want to TRY and turn num1 and num2 into floats.
If there is a value error, you want to return None . Else return the sum of num1 and num2 .

def add(num1, num2):
    try:
        # try and turn num1 and num2 into floats
        num1 = float(num1)
        num2 = float(num2)
    except ValueError:
        # return None if unable to convert
        return None
    else:
        # return the sum of num1 and num2 if they get converted to floats
        return num1 + num2

Thanks Colby. I'd been stuck on this question for over an hour. Sometimes when reading the question I picture how I'm meant to do it in a totally different way. Much appreciated.