Welcome to the Treehouse Community
Looking to learn something new?
Diego Crespo1,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
my bad I thought it posted the code. Thank you for the help, I was able to figure it out.
Haider AliPython Development Techdegree Graduate 24,724 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.
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.
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
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!