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

Siddharth Chavan
Siddharth Chavan
2,426 Points

What is going on here? I can't figure out the problem

Either it's a bug or I'm an idiot, I'm guessing number 2

trial.py
try():
    def add(n1, n2):
        except(ValueError):
            return(None)
        else():
            return(float(n1)+float(n2))

1 Answer

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 Points
  • try, return and else don't take parentheses
  • You should put the try block inside of the function. You're not going to try defining this function, the function is definitely getting defined. But inside the function, when it gets called, you're going to try converting what gets passed in into a float. If someone passes in something that can be converted to a float, it won't throw an error. If it can't be converted to a float, it will throw an error, and then it will go into the except block. If except doesn't happen, we go into the else block where you can return the items added together.

Here is my version of it:

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