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

Sean Richardson
Sean Richardson
495 Points

Try & Except

Im struggling with getting the try block syntax right, I think

trial.py
def add(x, y):
try:
    x = float(x)
    y = float(y)
except ValueError:
    Print("Goose")
else:
    return float(x) + float(y)

2 Answers

On value error, you should return None as the problem states.

Also, in your last else statement, since you already redefined x and y as their floats, you don't have to return float(x)+float(y)

all in all:

def add(x,y):
   try:
      x = float(x)
      y = float(y)
   except ValueError:
      return None
   else:
      return x + y
Stuart Wright
Stuart Wright
41,120 Points

You are almost there. The main problem is that you need to indent everything that comes after the function header, so that the interpreter knows the code is all inside the function.

Your try/except/else logic is all correct, but you just forgot to return None inside the except block. You can print "Goose" as well if you like, but the challenge doesn't ask you to. If you choose to have a print statement here, it needs to be with a lower case p, as Python keywords are case-sensitive.

Edit: And as Travis says, no need to convert x and y to float in your final line, even though that would still pass the challenge.