简体   繁体   中英

how can i get input while it show list out of index

the code-> code the error-> error I can't get inputs it's showing List index out of range

n = int(input())
a = []
temp = input().split()
for i in range(n):
    a.append(int(temp[i]))
print(a)

Is this what you need?

n = int(input())
a = []
for i in range(n):
    a.append(int(input()))
print(a)

According to your input, which was "4" and "2", n = 4 temp = [2]

Then, the length of the list is 1 len(temp) = 1

I'm not sure what exactly you need from your code, but you can do it this way:

n = int(input())
a = []
for i in range(min(n, len(temp))):
    a.append(int(input()))
print(a)

Or you can also use exceptions:

n = int(input())
a = []
for i in range(n):
    try:
        a.append(int(input()))
    except IndexError:
        break
print(a)

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