Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

John Cuddihy
5,493 PointsHi learning about python in python basics, stuck on this lesson
def add(float num1,float num2):
sum = num1 + num2 sum=float(sum) return sum
at it so long now losing faith
def add(float num1,float num2):
sum = num1 + num2
sum=float(sum)
return sum
2 Answers

Jennifer Nordell
Treehouse TeacherDon't lose faith! You'll get the hang of it. Let me show you what you need then I'll walk you through it:
def add(num1, num2):
try:
return float(num1) + float(num2)
except ValueError:
return None
So first we declare our function which takes two pieces of input. Let's say we've asked our users to send us two numbers. Users though tend to hit incorrect keys or send things we don't ask for. So what we're going to do is first check to see that we can convert those two pieces of input to floats. If both pieces can be converted to floats we add the two numbers together then return the result of the addition. If either one of those pieces of input fails to convert to a float with a "ValueError" then we return None.
Hope that clears things up! When it gets difficult just try to remember why you worked this hard in the first place. Persistence generally pays off... eventually :)

Kourosh Raeen
23,732 PointsWhen defining a function you shouldn't specify any type for the formal parameters:
def add(num1, num2):
sum = num1 + num2
return sum
John Cuddihy
5,493 PointsJohn Cuddihy
5,493 PointsThanks Jennifer, I thought by defining the variables in the function it would suffice, but you live and learn
johnny
Haider Ali
Python Development Techdegree Graduate 24,724 PointsHaider Ali
Python Development Techdegree Graduate 24,724 PointsA Brilliant Explenation! Best answer selected
Daniel Holmes
2,765 PointsDaniel Holmes
2,765 Pointshere is the entire code including the one you gave me it still will not work
def add(x, y): # number 1 and 2 return x + y # number 3 def add(x, y): f_x, f_y = float(x), float(y) return f_x + f_y def add(num1, num2): try: return float(num1) + float(num2) except ValueError: return None