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

sai jayanth kashyap
sai jayanth kashyap
3,293 Points

what is wrong with this code?

error says "try again"

trial.py
def add(x,y):
try:
    return( float(x) + float(y))
except ValueError: 
    return None
else: 
    print(x + y)

2 Answers

Torsten Lundahl
Torsten Lundahl
2,570 Points

Just to clearify the task. You are supposed to convert the input to floats inside Try and then return them inside Else.

You're on the right path, but there are some things you need to have in mind.

Try - Used to try a piece of code. (In this case converting ints to floats)

Except - What should be done if the code inside Try doesn't work.

Else - If the code inside Try works, do this.

Hope you can figure it out :)

sai jayanth kashyap
sai jayanth kashyap
3,293 Points

thankyou, but I am still getting the same error. def add(x,y): try: x = float(x) y = float(y) except ValueError: return None else: return x + y

Jeff Wilton
Jeff Wilton
16,646 Points

Make sure your formatting and indentation is correct.

Should look something like this:

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