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

Steven Gutierrez
seal-mask
.a{fill-rule:evenodd;}techdegree
Steven Gutierrez
Full Stack JavaScript Techdegree Student 9,035 Points

Try Statement

How do I write the try statement here? is it within the add function or was i supposed to remove that?

trial.py
def add(num1, num2):
    try:

    except ValueError:
        return None
    else:
        return float(num1) + float(num2)

4 Answers

To elaborate, the try statement asks you to try to do something. So basicly you would do it like this:

try:
    num1 = float(num1)
    num2 = float(num2)
    return num1 + num2

So we are basicly asking python to try to do that. However imagine that num1 or num2 is a string. Well you cant turn a string into a float, and so its gonna throw a ValueError, because your trying to do something thats not possible.
But you can tell the computer to do something else if the try: spits out a ValueError. This is what the except does. It says except ValueError: Do this So you except should look like this:

except ValueError:
    return None

Finished code:

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

Hopefully that makes sense bro!

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,454 Points

You are very close. You need code in the try block. You can move the last return into the try block and remove the else

Ben Reynolds
Ben Reynolds
35,170 Points

It will be in the add function, in the try block. Someone might try to sneak a string into one of the parameters, so that's the place to "try" it and see if the resulting number will be something you can work with. So put that return statement in the try block. If it works, then it works and the sum is returned. Otherwise, it will drop to the except block and return None.

Double check the exercise requirements, you might not need that "else" block at al

Glad to help! You Can mark the question as "solved" by sellecting a "Best answer"