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 trial

Python Python Basics (2015) Logic in Python Try and Except

Hi 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

trial.py
def add(float num1,float num2):

   sum = num1 + num2
    sum=float(sum)
  return  sum

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Don'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 :)

Thanks Jennifer, I thought by defining the variables in the function it would suffice, but you live and learn

johnny

here 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

Kourosh Raeen
Kourosh Raeen
23,733 Points

When defining a function you shouldn't specify any type for the formal parameters:

def add(num1, num2):
  sum = num1 + num2
  return sum