Reputation: 17
Doing some homework for my basic python class. This week we are doing a quiz on dictionaries and I'm not quiet understanding it.
The question we have been posed is, Write a function print_nth_item(data, n)
that takes a list data and an integer n
as parameters and prints the nth item of the list data, assuming the first item corresponds to an n
of 0. However this time n
might not be a valid position in data, eg, asking for the 10th item in a list that only has 5 items will not work. If this occurs you should handle the exception error by printing the text "Invalid position provided".
I have tried but failed to answer the question. My code is:
def print_nth_item(data, n):
"""dddd"""
try:
if n in data:
print(data)
except:
print('Invalid position provided.')
I know this doesn't work but am I on the right track?
Upvotes: 2
Views: 841
Reputation:
n in data
will look for the value n
, not the index n
. To use n
as the index, use data[n]
.
Do this:
def print_nth_item(data, n):
"""dddd"""
try:
print(data[n])
except IndexError:
print('Invalid position provided.')
Upvotes: 0
Reputation: 2290
Since it is 0 index, n will give you n
'th element.
def print_nth_item(data, n):
"""dddd"""
try:
print(data[n])
except IndexError:
print('Invalid position provided.')
If you need bare n
th element (not index based on list) use n-1
Complete example:
data = [0,1,2,3,4,5]
n = 9
def print_nth_item(data, n):
"""dddd"""
try:
print data[n]
except IndexError:
print 'Invalid position provided.'
print_nth_item(data, n)
Upvotes: 3