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

Mohammad Syed Raihaan
Mohammad Syed Raihaan
1,358 Points

I'm not sure what this task wants me to do. Please help.

I'm confused on what Task 3 expects from me. What should I exactly do to pass this task? And please explain the 'try' and 'except' blocks.

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

1 Answer

Pete P
Pete P
7,613 Points

You're very close. Inside of the try block, you should be converting x and y into floats.

def add(x,y):
    try: 
        #  Convert x and y into floats here
    except ValueError:
        return None
    else:
        return x + y

The try block will fail if x or y is say, a string like 'Treehouse'. The exception will then be raised and 'None' will be returned. However, if the conversion is a success, the exception will be skipped over and you can simply return x + y.

Hope this helps. Let me know if you're still having trouble.