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

difficulty understanding add function

i cant seem to add the 2 arguments

trial.py
def add(name + product):

    add()

    return(name + product)

1 Answer

Hi Tan , To create or define a function in python. We start with def keyword.

The Challenge ask to create add function that takes 2 argument so def add ( firstargument , secondargument ):

After that It ask you to add together as total and return so return firstarugment + secondargument;

So The First Step Look Like This :

def add ( number1 , number2 ):
    return number1 + number2

and then it ask you to convert it to float so that it can add the decimal number. return float(firstargument) + float(secondargument)

So it look like this

def add ( number1 , number2 ):
    return float(number1) + float(number2)

After that it ask you to use Try Except that will handling the error aka exception. If ValueError Exception Throws aka happen we handling it with Except Keyword and return none. If no exception happen return the total value. So try : total = float(firstargument) + float(secondargument) except : return None else: return total

This is what we get in the final

def add ( number1 , number2 ):
    try:
        total =  float(number1) + float(number2)
    except ValueError:
        return None
    else:
        return total

Thanks :)