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

"try:" and built function

I don't know how to implement try and def function in it. I was worked as it wrote in instruction and it's wrong. I can't fix it because the attached chunk of code is not my logic it is just a results of following the instruction.

trial.py
def add(a, b):
    try:
        except ValueError:
            return(none)
        else:
    return(float(a) + float(b))

1 Answer

Ryan S
Ryan S
27,276 Points

Hi Juro,

When using a try: block, you need to try to do something in it. In this case, you are trying to see if your arguments "a" and "b" can be converted into a float. If they cannot (if they are non-numeric strings, for example), you will get an error. This is where the except ValueError: comes in, it will allow you to handle the error without breaking the code.

So the logic of the try/except blocks in this challenge would look something like this:

def add(num1, num2):
    try:
        #  try to convert num1 and num2 into floats
    except ValueError:
        #  If they cannot be converted and a ValueError is raised, handle it here.
    else:
        #  If the try block passed and no error was raised, return whatever you need to here.

Hope this helps.