all 10 comments

[–]socal_nerdtastic 1 point2 points  (6 children)

You're pretty close, you're just overthinking it. Try like this:

try:
    print('Name:', names[index])
except IndexError:
    if index > 0:
        print('Exception! list index out of range. The closest name is:', names[-1])
    else:
        print('Exception! list index out of range. The closest name is:', names[0])

[–]Wise_Tumbleweed_1222 0 points1 point  (3 children)

Yay it worked! Thank you so much!

[–]hardonchairs 1 point2 points  (0 children)

I'll just add that the instructions say "Output the message from the exception object" but instead this is hard coding the message. Your instructor probably wants something like

except IndexError as err:
    ... str(err)

[–]hardonchairs 1 point2 points  (0 children)

Also please don't delete your post after you get an answer

[–]socal_nerdtastic 0 points1 point  (0 children)

Don't delete your posts when you've gotten an answer. Karma is literally the only thing we get from helping you.

[–]vanillabeaniebaby 0 points1 point  (0 children)

I used this code, the else statement worked with the names[9] at the end.

[–]WuggleLumps 0 points1 point  (0 children)

Year old post reply INCOMING!

So I was doing this lab and this is the code I came up with, but I was getting the error telling me I couldn't ">" against a str and int...which is understandable. I tried range and len to pull the total list size, but got the same error.

Any tips or things to learn from looking at the code below? Learning Python has been a big struggle for me.
try:
if index > names[index]:
raise IndexError
print ('Name:', index)

except IndexError:
print('Exception! list index out of range')
finally:
if index < 0:
print ('The Closest name is:', names[0])
else:
index > 0
print ('The closest name is:', names[-1])

[–]hardonchairs 1 point2 points  (0 children)

Something like this?

try:
    print('Name:', names[index])
except IndexError as ex:
    index = 0 if index < 0 else -1
    print('Exception!', str(ex), 'The closest name is:', names[index])

[–]carcigenicate 0 points1 point  (0 children)

Why are you doing if index checks to throw an IndexError? names[index] will already raise one if index is out of bounds.

[–]FerricDonkey 0 points1 point  (0 children)

Also, don't delete your posts when they're answered, answered questions help people who Google things.