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

Diego Crespo
Diego Crespo
1,996 Points

try and except 1/3

I don't understand why it won't return the values added together even though I have defined them as integers.

def add(arg1, arg2):

arg1 = 1

arg2 = 2

total = arg1 + arg2

return total

my bad I thought it posted the code. Thank you for the help, I was able to figure it out.

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

The "post your code" isn't working. Can you please add your code manually?

1 Answer

Haider Ali
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Haider Ali
Python Development Techdegree Graduate 24,728 Points

I understand that you are having a problem with this challenge, as you have not specified which part exactly you are stuck on, I will explain each part of the challenge step by step.

Task 1:

def add(a, b):
    return a + b

This first task is simple, this function takes in 2 arguments which are integers. It adds them both together then returns the sum of them both.

Task 2:

In the second task, you have to convert the 2 arguments into floats before you add them. You can do this using the float() function. You can shorten this code by assigning both variables in one line. Either of the 2 solutions below will work:

def add(a, b):
    a = float(a)
    b = float(b)
    return a + b
def add(a, b):
    a, b = float(a), float(b)
    return a + b

Task 3:

Finally, in task 3, we need to handle a situation where instead of 2 integers, something like a string is passed in. We need to try to convert both arguments to floats. However, if there is a ValueError, we should return the value None. You can do this with the following code, I will add comments to explain what each part does:

def add(a, b):          #define function named add which takes 2 arguments
    try:                #try to do the following:
        a = float(a)
        b = float(b)
    except ValueError:  #If there is a ValueError
        return None     #return None because this means either one or both of the arguments are not an integer
    return a + b        #Finally, if there is no value error, add the two floats together and return the total

I hope i solved your problem and that you understand now!