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

Pol Marín
Pol Marín
1,108 Points

I don't know how to do the first part.I think that there could be different ways of doing it but none is accepted.

I dont know how to turn every number into a float, in the try part.

trial.py
def add(num1, num2):
    num1=float(num1)
    num2=float(num2)
    return(num1+num2)

try:
    add(1,2)
except ValueError:
    return None
else: 
    return(num1+num2)

2 Answers

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,887 Points

Hi Pol,

First of all, this try/except/else code is going in your function so that your function itself can perform the exception handling. Right now you are attempting to handle a single call to the function.

When implementing the try/else/except block, remember that a try block is where you put an expression that could fail. Specifically, in this case, converting a value from an unknown type into a float. You've already demonstrated how to do that type conversion with your num1 = float(num1). Since this is the code that could fail, this is what we want to put in the try block. For example:

try:
    num1 = float(num1)
<etc>

Since we want to convert perform the same type conversion on both values, we can actually do it as a tuple:

(num1, num2) = (float(num1), float(num2))

Your remaining code, the except block and the else block both look fine already.

Cheers

Alex

Elgene Ee
Elgene Ee
3,554 Points

Hi Pol, I do not seem to understand the situation quite well...what you wrote in the try block does not relate much. Could you show me the question or what are the challenge so I can help you out :)