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

code for challenge task 3 I want to know how to defind "try:" and how wrong this my code. thanks

code for challenge task 3 I want to know how to defind "try:" before or after "def". and how wrong this my code.thank you.

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

3 Answers

Russell Sawyer
seal-mask
.a{fill-rule:evenodd;}techdegree
Russell Sawyer
Front End Web Development Techdegree Student 15,705 Points

You're pretty close. Your try: needs to be inside the function. The try just verifies that the numbers are not strings. If they are then the ValueError: will return None. else: return the sum of the floated numbers.

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

thank you so much. and after "return" shound I use the parentheses around "None", "num1 + num2" or write the code same your code.

Russell Sawyer
seal-mask
.a{fill-rule:evenodd;}techdegree
Russell Sawyer
Front End Web Development Techdegree Student 15,705 Points

With return values you don't use parentheses. You do, however, use parentheses with print(). But in this challenge they are asking you to return the values.

thanks for your suggestion that help me a lot.