简体   繁体   中英

Print n-th item

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?

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)

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.')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM