Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics (2015) Logic in Python Try and Except

tom shennan
tom shennan
1,718 Points

What's wrong with my code??

Hey guys, I've been stuck on this challenge for a bit now, I can't figure out what's wrong with what I've done, any help will be appreciated, thanks.

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

1 Answer

andren
andren
28,538 Points

Your code is correct syntax wise, but the indentation (horizontal spacing) is incorrect. In Python indentation is used to group code and it is essential to get it right. Since the try/except/else blocks are supposed to be a part of the add function they have to be indented to be inside of it.

If you fix the indentation like this:

def add(x, y): 
    try:
        arg1 = float(x) 
        arg2 = float(y)
    except ValueError: 
        return None 
    else: 
        return (arg1 + arg2)

Then your code will work.