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

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?


3 Answers

Nathan Tallack
Nathan Tallack
22,159 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):
        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)