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

how to use try: after def functions

i did this code but it gives me an error I need to know what is wrong and how to fix it to go to next lesson

def add(num1, num2): try: add(num1, num2) except ValueError: return None else: return float(num1)+float(num2)

trial.py
def add(num1, num2):
    try:
        add(num1, num2)
    except ValueError:
        return None
    else:
        return float(num1)+float(num2)

1 Answer

Tobias Edwards
Tobias Edwards
14,458 Points

If you called your add() function , the first thing it would do is within the try block - and it would call the add() function again (so the program would be stuck in an infinite loop if two numbers were passed into the function).

To fix this, I would try converting num1 and num2 into floats within the try block. Then simply return num1 + num2 in the else block.

def add(num1, num2):
    try:
        num1 = float(num1)
        num2 = float(num2)
    except ValueError:
        return None
    else:
        return num1 + num2

can you show me how to do that since this was the task(Add a try block before where you turn your arguments into floats. Then add an except to catch the possible ValueError. Inside the except block, return None. If you're following the structure from the videos, add an else: for your final return of the added floats.)

Tobias Edwards
Tobias Edwards
14,458 Points

I've updated my answer for you

Thank you so much for the answer.. Best regard