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

What's wrong with this code?

couldn't find the solution

trial.py
def add(a,b):
    try:
        a = int(a)
        b = int(b)
    
    except ValueError:
        return None
    a = float(a)
    b = float(b)
    return a + b

1 Answer

Stuart Wright
Stuart Wright
41,118 Points

I think that your code should work but it includes an unnecessary step, which may be why it doesn't pass the challenge.

There is no need to convert a and b to integers. Simply convert them straight to float form inside your try block. Your except block is correct. Then just delete the float conversion statements at the end of your program because they are now unnecessary. The return statement is correct.

Hi thanks a lot for taking your time to answer my doubt. Yeah initially what i did was putting the float instead of int. But it didn't work out. So it tried it out with int. After reading your answer i went back the question again. Redo it again. And it works. The reason why it didn't pass the challenges was because of the indentation at the last return there. notice that i didnt indent it initially. Anyway Thanks for your help :D