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

Amr AbdelNasser
Amr AbdelNasser
1,745 Points

combining functions and exceptions

can't figure out, how to add an exception with the set function without getting the "Task one is no longer valid" notification. Whats wrong with my code?

trial.py
def add(e,r):
try:
    e=int(input)
    r=int(input)
except ValueError  
    return None
else:
    return (float(e)+float(r))

2 Answers

def add(x,y):
    try:
        return float(x)+float(y)
    except ValueError:
        return None
Amr AbdelNasser
Amr AbdelNasser
1,745 Points

that makes a lot of sense, but it still doesn't seem to work. Getting the same message of "Task 1 no longer passing" and i think the exercise requires an "else".

No it works, I tried it.

Alright, I think I may have an answer

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

YouΒ΄re basically using the else to repeat the first step in case it didn't work for any reason. I tried running it in the Code Challenge and it marked it as a correct solution.

Hope you understand, if not just tell me and I'll try to clarify for you.

why are you returning the same thing in two different areas?? that is terrible advice.

Quite true... So then it should work fine without it but I still don't understand what the code challenge means by using the else structure at the end. What should go on the else? I mean, I understand that the code works the same with or without the else but why is it part of the challenge to use else??

else is english semantics except is the programatic representation when you are trying to trap an error.