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 trialoliverchou
20,886 Pointswhat's wrong with it?
def add(x, y): return(float(x) + float(y)) try: add(x, y) except ValueError: return(none) else: return(add(x, y))
def add(x, y):
return(float(x) + float(y))
try:
add(x, y)
except ValueError:
return(none)
else:
return(add(x, y))
1 Answer
Jennifer Nordell
Treehouse TeacherHi oliverchou ! You did great right up until the last step. And even then, you're not that far off. One thing to note though, it's generally not a good idea for a function to call itself. This can lead to infinite recursion. Let me show you my solution and then walk you through what it's doing:
def add(x, y):
try:
return float(x) + float(y)
except ValueError:
return None
Our add function is going to accept two inputs. Now, we hope that they are numbers. But users are unpredictable and make typos sometimes. So we want to make sure that what they put in, is actually a number.
So first we try
to convert both inputs into floats. If that works, we add them together and return the result. However, if we get an exception of ValueError
(this means the user typed in something like E and 2) then we return None
. Hope this helps!
oliverchou
20,886 Pointsoliverchou
20,886 PointsGot it! just simply put all script into that "add" function thanks! :)