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

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 :)