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 trialTodd East
Courses Plus Student 3,602 Pointswhy does this code trip a ValueError?
def add(num1,num2): total=float(num1+num2) return(total)
def add(num1,num2):
total=float(num1+num2)
return(total)
1 Answer
jacksonpranica
17,610 PointsHey Todd,
Wasn't really sure what value error was occuring as it worked in my local python environment. However, when doing the code challenge I found where the problem lied.
So in the code challenge it says to turn your arguments into floats using float() BEFORE you add them. Meaning you should be doing:
def add(num1,num2):
total=float(num1)+float(num2)
return(total)
EDIT: just realized num1 and num2 are strings and thats why float(num1+num2) doesnt work because it makes one giant string that cant be turned into a float due to the + sign. Ignore the explanation below
So why is float(num1+num2) wrong? Well it seems in the code challenge the software is taking (num1+num2) as a string due to the + sign. So obviously a string of "num1+num2" cant be converted to a float because a "+" does not have a numeric value.
As i was saying, in my local python environment on my computer num1+num2 is completed and turned into a numeric value before they try to turn it into a float. Im not sure why the code challenge takes it as a string due to the +
Cheers
Todd East
Courses Plus Student 3,602 PointsTodd East
Courses Plus Student 3,602 PointsThank you, that makes sense.