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 trialor porat
684 Pointsadding "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!
def add(pizza, icecream):
try:
return float(pizza) + float(icecream)
1 Answer
Alexander Davison
65,469 PointsThe 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:
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:
- 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 offloat(a) + float(b)
successfully. - If it does cause a
ValueError
, though, that means that eithera
orb
isn't able to convert into a float. In that case, you just returnNone
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
684 Pointsor porat
684 Pointshey 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 :\
Alexander Davison
65,469 PointsAlexander Davison
65,469 PointsTo 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:
Can you try posting code now?