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

Panos Kokoropoulos
Panos Kokoropoulos
966 Points

how to incorporate try box in basic python challenge

Challenge requires defining a function "add" which returns the sum of two numbers. 2nd step requires making the two numbers floats before adding. These two steps are solved. It then says to add a "try block" with an "except ValueError" statement which returns None and an "else" statement which returns the sum of the floats. Have tried every way I can think of to incorporate "try block" without success. Any ideas?

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

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,454 Points

There are a couple of ways to solve this. Currently your code has improper indentation and there is no content to the try code block:

def add(num1, num2):
    # Indent function code block
    try:  
        # Add try block content to convert and add arguments
        result = float(num1) + float(num2)
    except ValueError:
        # exception hit during try block, return 'None'
        return None
    else:
        # return the result if the try did not raise an error
        return result