xian123 发表于 2018-9-21 08:17:49

Python-IndexError: list index out of range

  Error:IndexError: list index out of range
  Where?
  对Python中有序序列进行按索引取值的时候,出现这个异常
  Why?
  对于有序序列: 字符串 str 、列表 list 、元组 tuple进行按索引取值的时候,默认范围为 0 ~ len(有序序列)-1,计数从0开始,而不是从1开始,最后一位索引则为总长度减去1。当然也可以使用 负数表示从倒数第几个,计数从-1开始,则对于有序序列,总体范围为 -len(有序序列) ~ len(有序序列)-1,如果输入的取值结果不在这个范围内,则报这个错
  Way?
  检查索引是否在 -len(有序序列) ~ len(有序序列)-1 范围内,修改正确
  错误代码:
  

name = "beimenchuixue"  
students = ["beimenchuixue", "boKeYuan", "Python", "Golang"]
  
print(name)
  
print(students)
  

  

  正确代码:
  

name = "beimenchuixue"  
students = ["beimenchuixue", "boKeYuan", "Python", "Golang"]
  
print(name)
  
print(students)
  

  



页: [1]
查看完整版本: Python-IndexError: list index out of range