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

Małgorzata Staniszewska
Małgorzata Staniszewska
2,431 Points

what is wrong with my code?

?

trial.py
def add(a,b):
    try:
        except ValueError:
            return(None)
        else:
            return(float(a)+float(b))
Rustam Ismailov
Rustam Ismailov
6,234 Points

Try to use this format :

  1. first you define the function
  2. then in try to create a value total and assign a floated sum of num1 and num2 to it
  3. run except block
  4. return total
def add(num1, num2):
    try: total = float(num1)+float(num2)
    except ValueError:
        return None
    else:
        return total

1 Answer

andren
andren
28,558 Points

You have the structure of try statements slightly off, a try statement is structured like this:

try:
    #CODE TO BE TRIED
except #ERROR TYPE:
    #CODE TO BE RUN IF ERROR OCCURS
else:
    #CODE TO RUN IF ERROR DOES NOT OCCUR
# It is important to note that try, except and else all need to be on the same indentation level.

In your code you are not actually providing any code to be tried, and you have also placed the except and else statement within the try block indentation wise which is incorrect.

The solution to this task looks like this:

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

In the above code I don't to anything useful inside the try block, I just convert a and b to floats without actually storing the result of that conversion anywhere, but that is fine since the point of the try clause in this instance is just to see if a and b can be converted to floats without causing any errors. If they can be then the code within the else clause is executed, if they can't then the code within the except clause is executed.