我是靠谱客的博主 爱笑火,最近开发中收集的这篇文章主要介绍python index out of bounds,Python错误代码:IndexError:索引错误列表索引超出范围,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

I'm trying to write a function in Python that simulates a horse race. While there's no winner, it clears the screen, shows the list of horses (all have index starting at zero). Then, on the line I've marked, the code messes up.

I get the index error list out of range. I'm trying to randomly pick a horse (randomly pick an index number) and add 1 to the value. But I can't seem to figure it out!!

while (no_winner):

os.system("cls")

print(horses)

# randomly assign a horse to step forward

rando = random.randint(1, HORSE_NUM)

horses[rando] += 1 #######PROBLEM

# if the horse exceeds the finish line, he wins

if (steps > FINISH_LINE):

winner = horses[index]

no_winner = False

解决方案

random.randint() is inclusive, so if you get a random integer that is equal to HORSE_NUM it will be out of bounds. try

rando = random.randint(0, HORSE_NUM - 1)

最后

以上就是爱笑火为你收集整理的python index out of bounds,Python错误代码:IndexError:索引错误列表索引超出范围的全部内容,希望文章能够帮你解决python index out of bounds,Python错误代码:IndexError:索引错误列表索引超出范围所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部