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

Alice Ng
Alice Ng
1,560 Points

Catch and Try Question(PYTHON BASICS)

I have no idea how this can be solved

trial.py
def add(x,y):
try int(x),int(y)
except ValueError:
    return none
else:
    x1 = float(x)
    y1 = float(y)
    return x1+y1

2 Answers

Ari Misha
Ari Misha
19,323 Points

Haha of course it wont coz its not indented. I didnt write code in the challenge editor, i wrote here in the comment section , so it must have unindented it whilst posting. I've edited it and tested it. Now you can submit the very same code. Here ya go (:

def add(x, y):
    try:
        x = float(x)
        y = float(y)
    except ValueError:
        return None
    else:
        return x + y 
Alice Ng
Alice Ng
1,560 Points

Thanks, looks like i have to get my indentation right. Great help

Ari Misha
Ari Misha
19,323 Points

Hiya Weihao! Looks like you've SyntaxError and few other errors as well. First off, "try" block is used where you know statement(s) might throw an unexpected error coz yeah it happens in programming where you're unsure about behaviour of your code and the result you get might surprise ya. So you could always put the statement(s) in try block. And capture with "except" whatever the error your try block throws at ya. And it pretty much controls the flow of your application or class or loops. And Then followed by "else" block, which is different than else in if-else block , the "else " block gets executed anyway even if your try block doesnt throw any error..

Now regarding your code and challenge. Summing it all together, your code should look like this:

def add(x,y):
try :
  x = float(x)
  y = float(y)
except: ValueError:
    return None
else:
  return(x + y)
Alice Ng
Alice Ng
1,560 Points

Thank you so much for answering my question!!

Alice Ng
Alice Ng
1,560 Points

I tried the same thing as you did and it still didnt work