【问题标题】:Simple python program - stuck简单的python程序 - 卡住了
【发布时间】:2015-08-13 22:39:27
【问题描述】:

我正在编写这段代码,它说明我放置的人是否有高分。

当我在列表中添加一个人(例如“雷神”)时,它可以正常工作,但是如果该名称不在其中,则程序不会捕获错误并且不会打印“不,他们没有最高分”列表。

Names = ['Ben', 'Thor', 'Zoe', 'Kate']
Max = 4
Current = 1
Found = False
PlayerName = input("What player are you looking for? ")
while (Found == False) and (Current <= Max):
    if Names[Current] == PlayerName:
        Found = True
    else:
        Current = Current + 1
if Found == True:
    print("Yes, they have a top Score")
else:
    print("No, They do not have a top score")

所以如果以 James 为例,它会输入这个错误

if Names[Current] == PlayerName:
IndexError: list index out of range"

我该如何解决这个问题?谢谢。

【问题讨论】:

  • 列表从零开始,更改为 Current &lt; Max,您将在 0、1、2、3(总共 4 个元素)上运行。
  • 感谢它完美运行,我该怎么办?关闭问题还是?
  • @MarounMaroun 我只是看到您在评论中回答的问题比我之前的问题。所以我删除了我的答案。 :) 请张贴。它是你的 :)
  • @Abraham 没关系,你撤消删除:) 你发布了一个很好的解释。
  • if PlayerName in Names: 是比 while 循环更简洁的解决方案。

标签: python list integer range


【解决方案1】:

您的数组索引从1 开始,而在Python、C、C++ 和许多语言中,数组索引(例如列表)从0 开始并以ArrayLength - 1 结束。将循环更改为:

while (Found == False) and (Current < Max):
                                    ↑

【讨论】:

    【解决方案2】:

    Max 应该是 3 而不是 4。 不要忘记数组是 0 索引的,所以 Names[3] 指的是第 4 个元素(也是最后一个)

    并且从0开始Current=0

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-06
      • 1970-01-01
      • 2017-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多