[Python] Nth item, Nth square

Asked 2 years ago, Updated 2 years ago, 19 views

def abc(array, N):

    if array[N] in array:
        return array[N-1]**N
    else:
        return (-1)
print(abc((1,2,3,4,5,6),3))

The result is good up to 5, but why does the result get weird from 6?

python

2022-09-21 11:50

2 Answers

(1,2,3,4,5,6) Length is 6. And it starts with zero.

That is, a = (1,2,3,4,5,6) a[0] is 1.

It can be accessed from 0 to 5, but if you put 6, it will exceed the access range, so an error will occur.


2022-09-21 11:50

The format is as follows.

That is, you can put return -1 in the exception.

try:
    a = (1,2,3,4,5,6)
    ...
except IndexError:
    # Handle when index is out of bounds


2022-09-21 11:50

If you have any answers or tips


© 2025 OneMinuteCode. All rights reserved.