I wrote some code and it's not running correctly. It's supposed to follow the example. Can someone help me figure out what I did wrong? Thank you.
>>> nth_item(['one', 'two', 'three'], 1)
'one'
>>> nth_item(['one', 'two', 'three'], 3)
'three'
>>> nth_item(['one', 'two', 'three'], 0)
>>> nth_item(['one', 'two', 'three'], -1)
>>> nth_item(['one', 'two', 'three'], 1, reverse=True)
'three'
def nth_item(item_list, n, reverse=False):
length = len(item_list)
if n < 1 or n > length:
return None
if reverse:
return item_list[length-n]
return item_list[n-1]
pass
CodePudding user response:
I run the same function and parse the return values into multiple variables (a
,b
,c
,d
,e
). I only removed the pass
statement as it would never be used.
def nth_item(item_list, n, reverse=False):
length = len(item_list)
if n < 1 or n > length:
return None
if reverse:
return item_list[length-n]
return item_list[n-1]
# run the function
a = nth_item(['one', 'two', 'three'], 1)
b = nth_item(['one', 'two', 'three'], 3)
c = nth_item(['one', 'two', 'three'], 0)
d = nth_item(['one', 'two', 'three'], -1)
e = nth_item(['one', 'two', 'three'], 1, reverse=True)
# show results
print(a)
print(b)
print(c)
print(d)
print(e)
and these are the results:
one
three
None
None
three
This works fine, so were you expecting something different ?