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 trialJohn 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,733 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,728 PointsHaider Ali
Python Development Techdegree Graduate 24,728 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