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

Samuel Focht
Samuel Focht
4,321 Points

Can't pass trial.py

Keep getting error, can't find my mistake.

trial.py
def add(x, y):
    try:
        return x + y
    except ValueError:
        return None
    else:
        return float(x) + float(y)

1 Answer

Samuel Ferree
Samuel Ferree
31,722 Points

The float function is what might be throwing the ValueError, but you're calling it outside your try block. To ensure that any value errors are caught, called the float function in the Try block like so

def add(x, y):
  try:
    fx = float(x)
    fy = float(y)
  except ValueError:
    return None
  else:
    return fx + fy # <-- Remember to use the floats we created earlier

Per the challenge, although it's good practice, you don't actually need to convert the values to floats and catch any errors.

Thus, the code can be simplified to just

def add(x, y):
  return x + y
Samuel Focht
Samuel Focht
4,321 Points

Thank you very much now see what we are trying to accomplish. Thanks again.