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

Erin Kross
Erin Kross
9,555 Points

what am i supposed to be trying in the try block?

It is not clear to me what I am meant to be trying in the try block for this task. Am I meant to try converting a non-number into a float?

trial.py
def add(arg1, arg2):
    try: 
        float(arg1)
        float(arg2)
    except ValueError:
        return('None')
    else:
        return(float(arg1) + float(arg2))

1 Answer

Here is an example of my code:

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

I am telling Python to try and return the addition of two floats. If Python raises a ValueError I will return None instead.

Python raises a ValueError if num1 or num2 is not:

  1. An integer
  2. A float
  3. A string of an integer ("12")

If you have any other questions I will update my answer, if you do not have any other questions:

Remember to upvote and to choose the best answer so that your question receives a checkmark in forums.

Kind regards,

Leo

Erin Kross
Erin Kross
9,555 Points

Thank you so much. this definitely helps!