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

or porat
or porat
684 Points

adding "try" to my code

hey! its ask me to add 'try' to the code but i didnt realize what to write after it. in the video i saw a line that came after the 'try', but here i didnt understood how to use it. ill be happy to get some help

thanx!

trial.py
    def add(pizza, icecream):
        try:

    return float(pizza) + float(icecream)

1 Answer

The try block doesn't really do anything unless it is used with a except block, too.

The except block is only run if the code in thetry block causes an error in some way.

Maybe icecream was a string and can't be converted to a float and it causes a ValueError.

Try this:

trial.py
def add(a, b):
    try:
        return float(a) + float(b)
    except ValueError:
        return None

Don't worry if you can't understand this code perfectly; I'll explain it step-by-step:

  1. First we are testing and see if returning float(a) + float(b) will cause an error. If it doesn't, well, great. The function just returned the value of float(a) + float(b) successfully.
  2. If it does cause a ValueError, though, that means that either a or b isn't able to convert into a float. In that case, you just return None like what the challenge ask to do.

Also, I personally don't really like using the else part of an try/except block, but if you want to use it the code will look like this:

def add(a, b):
    try:
       value = float(a) + float(b)
    except ValueError:
        return None
    else:
        return value

I hope you understand now!

Good luck!

~Alex

If you have any questions please ask me below. I'd be happy to answer :)

or porat
or porat
684 Points

hey alex thanx! but still it doesnt work im trying exacly how you said to me.. ill upload the pic with the qustion agine because i dont know how to do it here in the comments :\

To post code in the comments, you add ```python and ``` around the code, like this:

```python

# Your Python code goes here

print("Hello World!")

```

This will look like this in when you post the comment:

# Your Python code goes here
print("Hello World!")

Can you try posting code now?