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 trialV G
3,087 PointsWhat's wrong with this code?
I think something is wrong with the try block.
def add(a, b):
return(float(a) + float(b))
try:
float(input(a, b))
except ValueError:
return None
else:
return(a + b)
2 Answers
Ben Slivinn
10,156 PointsThe logic is that you get the input from the add function itself, add(a, b), so there is no need in return(float(a) + float(b)) anymore, same for float(input(a,b)) Then you check with try\except the data provided to the function, you assign the input to a float. If it's not possible then python will rise ValueError that we will catch with 'except', and return None. Every other possibility will add both numbers, and as they already assigned as floats, we will return float value.
def add(num1, num2):
try:
num1 = float(num1)
num2 = float(num2)
except ValueError:
return None
else:
num = num1 + num2
return num
Ben Slivinn
10,156 PointsSorry, but I missed that you are talking about task 3... Please check my edited answer, I hope its all clear now. Good luck!
V G
3,087 PointsV G
3,087 PointsThanks