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 trialSiddharth Chavan
2,426 PointsWhat is going on here? I can't figure out the problem
Either it's a bug or I'm an idiot, I'm guessing number 2
try():
def add(n1, n2):
except(ValueError):
return(None)
else():
return(float(n1)+float(n2))
1 Answer
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 Points-
try
,return
andelse
don't take parentheses - You should put the try block inside of the function. You're not going to try defining this function, the function is definitely getting defined. But inside the function, when it gets called, you're going to try converting what gets passed in into a float. If someone passes in something that can be converted to a float, it won't throw an error. If it can't be converted to a float, it will throw an error, and then it will go into the
except
block. Ifexcept
doesn't happen, we go into theelse
block where you can return the items added together.
Here is my version of it:
def add(n1, n2):
try:
float_sum = float(n1) + float(n2)
except ValueError:
return None
else:
return float_sum