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

Can someone help me with try: ?

Can someone just tell me what I am doing wrong with this task and tell me the right code so i can dissect it and see what I did wrong?

trial.py
def add(var1, var2):
    try:
    except ValueError:
        return None
    else:
        return float(var1) + float(var2)

total = add(2, 8)
print(total)

3 Answers

Steven Parker
Steven Parker
231,236 Points

For a "try" to work, the code that performs the operations that may generate exceptions (such as what is currently after "else") must be in the indented block immediately after the "try" (and before the "except").

After re-arranging the code, you won't need the "else":

def add(var1, var2):
    try:
        return float(var1) + float(var2)
    except ValueError:
        return None

And the challenge only requires you to define the function, you don't need to call it yourself or print anything.

Feisty Mullah
Feisty Mullah
25,849 Points

Hi Chase, Your code should look like this as if you go through the challenge from 1 - 3 it explains you what to do. I found that way easier.

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

Hi, I'm new to Python also, but I think this is what you're missing. Someone else might be able to explain better...

def add(var1, var2):
    try:
        #put code here to test, if it fails with a 'ValueError' it will execute the next line
    except ValueError:
        return None
    else:
        return float(var1) + float(var2)

total = add(2, 8)
print(total)