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

Have been struggling with this code challenge for days. Can someone tell me how to properly answer the 'Try and Except"?

This is for the third part of the challenge where you are asked for a bigger code writing section. I am not sure whether you are supposed to indent all code as per the function or if try (to check 'buggy' code) comes before the function. Also for return(None) is that meant to be return("None"). It is a really easy one but the right answer would be appreciated!

3 Answers

Nathan Tallack
Nathan Tallack
22,158 Points

Ok, it works like this.

def add(num1, num2):  # Here we take in two args
    try:  # If anything inside this block errors the except block will run
        f1 = float(num1)  # Trying to change our first arg to a float
        f2 = float(num2)  # Trying to change our second arg to a float
    except ValueError:  # If any of the try block returns a ValueError this except block runs
        return None  # If it runs our function returns None
    else:  # If the try block threw no errors this else block runs
        return f1 + f2  # We return the result of adding our two floats together

I hope this helps. Feel free to ask for any clarification if required. :)

Hi Eric, agreed the answer provided by Nathan was very helpful and clear. In answer to your question, the whole point of inserting a 'try' followed by an 'except ValueError' is to catch an error if it happens to be input into the function by the user. In this case, a ValueError would pop up if the user input a str() and not an int().

For example, only in the circumstance that either num1 or num2 (or both) were not int()s would the function then fail to convert the expected int()s into float()s and a ValueError would occur. Hopefully this demonstrates that a ValueError occurs as a result of finding an error in the try block where num1 or num2 are incompatible with float() conversion!

Eric Chan
Eric Chan
4,254 Points

Hi Nathan, thanks for providing the answer to this challenge. What I do not understand is this: When the float() function convert whatever value of num1 and num2 into float, will there still be a ValueError? Thanks