简体   繁体   English

如何在Python中修复“ IndexError:列表索引超出范围”

[英]How to fix “IndexError: list index out of range” in python

my problem is that when I set a for loop to look through a list it doesn't work because it is out of range, even when I start at 0. 我的问题是,当我设置一个for循环来浏览列表时,它不起作用,因为它超出了范围,即使我从0开始也是如此。

I have tried changing the range of the for loop but is isn't working. 我曾尝试更改for循环的范围,但无法正常工作。

Code = input("Enter your Key code: ")

Code = list(Code)

message = input("Enter your message: ")

message = list(message)

for i in (0, len(message)):
    if message[i] == Code[0]:
        message[i] = 'a'

I thought that it would work but it at the start of the for loop it breaks down. 我以为它可以工作,但是在for循环的开始它就崩溃了。

for i in (0, len(message)):

Should probably be 应该是

for i in range(len(message)):

You forgot the range 你忘了range

You want to do: 您想做:

for i in range(len(message)):
    ...

(0, len(message)) is a tuple. (0, len(message))是一个元组。 Iterating over this will give you 0 , then len(message) (which will always be 1 larger than the biggest valid index in your list), hence causing an IndexError. 对此进行迭代将为您提供0 ,然后为len(message) (始终比列表中最大的有效索引大1),从而导致IndexError。

You also probably want to check that Code has at least 1 character in it, otherwise Code[0] will also give you an IndexError. 您可能还需要检查Code是否包含至少1个字符,否则Code[0]也将为您提供IndexError。

Code = list(Code) or '?'

will set Code to '?' Code设置为'?' if Code == '' . 如果Code == ''

You made a typo 你打错字了

it should be like this: 应该是这样的:

for i in range(len(message)) 对于我在范围内(len(消息))

Your for loop is turple so it will always start from 1+ of what u want 您的for循环是弯曲的,因此它将总是从您想要的1+开始

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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