Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics (2015) Logic in Python Try and Except

task 3 try and except

i get error for this code please explain

trial.py
def add(num1,num2):
    try:
        float(num1)=num1
        float(num2)=num2

    except ValueError:
        return None
    else:
        return (float(num1)+float(num2))

1 Answer

Stuart Wright
Stuart Wright
41,102 Points

Your try block should look something like this:

try:
    num1_as_float = float(num1)
    num2_as_float = float(num2)

Your current version is not allowed because you are trying to assign to something which is not a variable name - "float(num1)". A variable name must always be on the left of an assignment statement, and a function such as float() can only be on the right.

Your except block is correct.

The else block is almost correct, except you just need to return the sum of your two new variables - they will already be converted to floats if your try block is correct, so there's no need to convert to float again.

else:
    return num1_as_float + num2_as_float

Thank you.