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

what mistake am I doing in this code?

I added try before I made the arguments into floats

trial.py
def add(in1, in2):
    try:
except ValueError:
    return None
else:
    in1 = float(in1)
    in2 = float(in2)
    return(in1 + in2)

1 Answer

Hey kevinkev

def add(in1, in2):
    try:
        # this is where you want to TRY to 
        # perform some operation or statement that
        # can potentially RAISE an exception

        # ex. something that would 'raise ValueError()'

except ValueError: # must be indented at same level as try-block
    return None
else: # also indent at same level as try-except block.
    in1 = float(in1)
    in2 = float(in2)
    return(in1 + in2)

So the question you ask yourself is which part of your code could potentially raise ValueError() ? That is the part you want to stick in the try block.

And in Python indentation is very important. It is how python figures out which code belongs inside a specific block. So be sure you make sure things are aligned where they need to be. :)

alright, thank you for taking your time to answer my question, really helped.

Awesome, glad you got it figured out! :)