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 trialLatoshia Wheeler
Courses Plus Student 778 PointsI don't understand why add is not defined in trial.py
i've tried a few variations of this code and I am getting bummer or add is not defined. However, when I do this code in the workspace it is fine. Can anyone find my bug and explain it to me? def add(x, y): try: x = float(x) y = float(y) total = x + y except ValueError: return none else: return total
add (2, 3)
def add(x, y):
try:
x = float(x)
y = float(y)
total = x + y
except ValueError:
return none
else:
return total
add (2, 3)
3 Answers
Afloarei Andrei
5,163 PointsYou'r problem is at "exept ValueError:" change the "return none" to "return None" or like Phillip Kerman said you can define 'none'.
Phillip Kerman
Courses Plus Student 285 PointsYou probably want the return total up inside the try (before "except"). The idea of try is you put EVERYTHING you want to happen in the try, and then handle problems afterward (in the "except" part).
Also, you can't return none unless "none" was previously defined. You can return a string ("none") if you want.
Kenneth Love
Treehouse Guest TeacherYou want to do as little as possible inside the try
. Only the code that might fail right away. You want to put things that should happen if there are no errors in the else
block.
Phillip Kerman
Courses Plus Student 285 PointsThanks Kenneth--I don't mean to give bad advice. What's the difference though if this were the code:
def add(x, y):
try:
x = float(x)
y = float(y)
total = x + y
return total
except ValueError:
return None
That is, just "return" inside the try? That's more familiar to me but it could be bad style?
Kenneth Love
Treehouse Guest TeacherFor something as simple as that snippet of code, no, it probably doesn't matter outside of consistency and personal style. For more complex pieces of code though, or code that can fail in multiple ways, keeping each block as small as possible really helps with making the code easier to understand and parse when reading it.
Latoshia Wheeler
Courses Plus Student 778 PointsLatoshia Wheeler
Courses Plus Student 778 PointsThanks guys it was the None. I appreciate all the help