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

Add a try block before where you turn your arguments into floats. Then add an except to catch the possible ValueError.

Hi I tried to solved this but I always get an error

This is the code

def add(num1, num2): try: float(num1)+float(num2) except ValueError: return None else: return float(num1)+float(num2)

How come this is wrong?

Thanks

3 Answers

Nathan Tallack
Nathan Tallack
22,158 Points

When you are pasting your code into the forum, try using the markdown so that the code formats correctly. That way we can see if there are any indentation problems with your code. Click the Markdown Cheatsheet below your input box for info on how this is done.

Consider how my code result for this challenge is formatted when displayed using correct Markdown.

def add(num1, num2):
    try:
        result = float(num1) + float(num2)
    except ValueError:
        return None
    return result

My code differs from yours in that I have moved the return outside of the try statement. So in my code I am assigning float(num1) + float(num2) result to a variable named result. Then if that works I am returning that result value. If it does not work in the try block then the ValueError will trigger an early return of None and the return result will not be executed by the function.

I think they call this "early return" or some such thing. :)

Hello! I've tried your code and it worked. Probably you have to indent smth. Good luck!

Thomas Souza
Thomas Souza
7,943 Points

def add(a, b): try: x = float(a) y= float(b) count = x + y except ValueError: return None else: return (count)