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 trialNader Alharbi
2,253 PointsMy take on fixing ZERO position
Hello everyone.
I wanted to share my code solving the problem if the user enter index #Zero In the original code if '0' is used the function would deduct '1' and you would have index '-1'
try:
position = abs(int(position))
if position == False:
raise ValueError
except ValueError:
position = None
if position is not None:
shopping_list.insert(position - 1, item)
else:
shopping_list.append(new_item)
show_list()
I hope it helps.
1 Answer
Steven Parker
231,236 PointsWouldn't inserting something at the -1 position make it second to last (when you want it to be first)?
Nader Alharbi
2,253 PointsNo it cannot be since you are taking the absolute of any given location.
position = abs(int(position))
Steven Parker
231,236 PointsI was talking about the calculation performed when a "0" is entered. As you said, "if '0' is used the function would deduct '1' and you would have index '-1'". It's that -1 that you pass on to "insert" that would place the item at the second-to-last position.
Nader Alharbi
2,253 PointsOh no, i'm raising a value error and excepting it to set position to None.
Steven Parker
231,236 PointsOh, I get it. Comparing a numeric value to "False" was a bit confusing. And the indentation seems off ("try" and "except" should always line up).
Now that I understand what's happening, you could condense it a bit:
try:
position = abs(int(position))
except ValueError:
position = 0
if position > 0:
shopping_list.insert(position - 1, item)
else:
shopping_list.append(new_item)
show_list()
Nader Alharbi
2,253 PointsThank you Steven, you are a blessing :)
nakalkucing
12,964 Pointsnakalkucing
12,964 PointsNeat! I haven't tested it yet, but it looks like a neat concept.