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

i am stuck do not know how to solve this

answer was not correct

trial.py
def add(apple,samsung):
try:
    return float(apple) + float(samsung)
    except ValueError():
else:    
    return (apple+samsung)

2 Answers

Jeff Wilton
Jeff Wilton
16,646 Points

You were close, I just corrected the indentation, and caught the ValueError as the argument to the except block and returned None as instructed:

def add(apple,samsung):
    try:
        return float(apple) + float(samsung)
    except (ValueError):
        return None
    else:    
        return (apple+samsung)

But why you make ValueError as argu. in challenge and also in videos they don't this....!

Jeff Wilton
Jeff Wilton
16,646 Points

You are correct, the except block is better as simply

except ValueError:
Daniel Bourke
Daniel Bourke
3,870 Points

Your code is almost correct! Just a few changes and you should be able to pass the challenge.

I'd say try and reformat it to make except have its own block.

def add(a, b):
    try:
        total = float(a) + float(b)
    except ValueError:
        return *Something*
    else:
        return total

So you end up with three blocks within the add function, try, except and else. The challenge asks you to return something within the except block.