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

Akhil Dogra
Akhil Dogra
444 Points

solution

Hey, I have been trying to solve this problem for a lot of time now . i have tried this in my python 3.5 idle too yet it is showing an error

trial.py
def add(a,b):
    try:
        int(a)
        int(b)
        except ValueError:
            return None
        else:
            return float(a)+float(b)

3 Answers

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

Hi Akhil,

In this challenge you nee to record the floated values before you add them together in order to get the code to work in challenge 3 of 3. If you float the numbers in the return statement you won't be able to separate them later and have the challenge except the answer.

  def add(num1, num2):
    num1 = float(num1);
    num2 = float(num2);
    return num1 + num2; 

Then in challenge 3 or 3 you will be able to test that the numbers are not strings in the try: and then return the floated values if the numbers are integers.

def add(num1, num2):
    try:
        num1 = float(num1);
        num2 = float(num2);
    except ValueError:
        return None
    else:
        return num1 + num2;
Kyler Smith
Kyler Smith
10,110 Points

You're close, but I think you are over thinking a little. There is no need to convert to an int() as in the 'try' block. It is asking to try and add together 2 numbers that are converted into floats. So, in the parameters (a and b), there should always be numbers. If the parameters are passed strings or anything that can't be converted to a float, you would get the ValueError. So in the 'except' block should return None. The else statement in this situation is not needed.

Kristian Gausel
Kristian Gausel
14,661 Points

No need to overthink this one. In the try block, assume everything works. Then in the except block just do as the question asks, and return None

def add(a,b):
    try: return float(a) + float(b)
    except ValueError: return None