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

Cannot get passed try:

I have tested this in the terminal with success, but for whatever reason it won't accept the answer here. Please see code.

trial.py
def add(one, two):
  try:
    three = one + two
    test = int(three)
  except ValueError:
    return(None)
        fone = float(one)
        ftwo = float(two)
        fthree = fone + ftwo
        return(fthree)

3 Answers

Martin Cornejo Saavedra
Martin Cornejo Saavedra
18,132 Points

I arranged your code, I don't know why you have repeated code from the previous task, and there were some identation errors, also there was no else: statement (not neccessary in try-except, but the challenge mentioned it).

def add(one, two):
  try:
    fone = float(one)
    ftwo = float(two) 
  except ValueError:
    return(None)
  else:
    fthree = fone + ftwo
    return(fthree)
Chris Freeman
Chris Freeman
Treehouse Moderator 68,454 Points

Please no parens in return statement unless required.. It is a keyword not a function.

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,454 Points

The last four lines of your code has an indentation issue. What are the last 4 lines intended to do? Did you mean to put and else: statement above them?

Your current code would fail because the conversion to floats add('4.5', '5.5')since thetrywould concatenate them to '4.55.5' and fail to convert to int, then returnNone` instead of converting to float.

Starting with Task 2, the challenge wants you to assume all addition be of floats. This means converting to float in the try section.

def add(one, two):
  try:
    three = float(one) + float(two)
    # test = int(three)
  except ValueError:
    return None  # <-- return does not need parens
  else:  # <-- added 'else'
        # fone = float(one)
        # ftwo = float(two)
        # fthree = fone + ftwo
        # return fthree   # <-- return does not need parens
        return three

Additionally, the return three can be moved into the try block and eliminate the else:

def add(one, two):
    try:
        # three = float(one) + float(two)
        # return three
        return = float(one) + float(two)
    except ValueError:
        return None

Many thanks!