Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Joshua Langtry
Joshua Langtry
370 Points

Final Python Basics Quiz Task

I am unsure how to use the final "else:" statement. I am so unsure that I don't know how else to define my question other than to say I don't know why it is not working. Please see code below.

Be my hero?

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

2 Answers

Thomas Fildes
Thomas Fildes
16,201 Points

Hi Joshua,

I think the problem might be with the indentation of your except but I am not too sure. Please see the code I used to pass this challenge below:

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

I found it a lot easier storing the floated numbers added together as a variable to make it look easier to read.

Christopher Shaw
seal-mask
PLUS
.a{fill-rule:evenodd;}techdegree seal-36
Christopher Shaw
Python Web Development Techdegree Graduate 58,236 Points

At first glance, your indentation does not make sense.

Also the else case is never reached as it will return in either the try or except.

So rremoving the else case and sorting the indentation we get:

    try:
        return(float(num1) + float(num2))
    except ValueError:
        return None