【发布时间】:2017-12-01 14:41:15
【问题描述】:
def main():
infile = open('charge_accounts.txt', 'r')
chargeAccounts = infile.readlines()
index = 0
while index < len(chargeAccounts):
chargeAccounts[index] = chargeAccounts[index].rstrip('\n')
index += 1
userAccount = input("Please enter a charge account number: ")
count = 0
while userAccount != chargeAccounts[count] or chargeAccounts[count] == chargeAccounts[17]:
count += 1
if chargeAccounts[index] == userAccount:
print("The account number", userAccount, "is in the list.")
else:
print("The account number", userAccount, "in not in the list.")
main()
我正在尝试在 python 中编写一个代码,让用户输入一个数字并检查该数字是否在列表中。当我尝试运行此代码时,我收到一条错误消息,指出列表索引在 while 循环中超出范围。列表中只有 18 个项目,我将 while 循环设置为在 17 处终止(列表中应该是 18)。
编辑:如果将 while 循环设置为 chargeAccounts[count] != chargeAccounts[17]:
这是确切的错误代码:
Traceback (most recent call last):
File "F:/CPT 168/Ch 7/AndrewBroughton_Chapter7_Excersizes/7-5/7-5.py", line 23, in <module>
main()
File "F:/CPT 168/Ch 7/AndrewBroughton_Chapter7_Excersizes/7-5/7-5.py", line 13, in main
while userAccount != chargeAccounts[count] or chargeAccounts[count] != chargeAccounts[17]:
IndexError: list index out of range
这是原始文本文件的内容:
5658845
4520125
7895122
8777541
8451277
1302850
8080152
4562555
5552012
5050552
7825877
1250255
1005231
6545231
3852085
7576651
7881200
4581002
【问题讨论】:
-
您有几个 while 循环,发布您的确切错误代码并通过向我们提供原始数据使问题可重现。似乎您在不检查它是否低于chargeAccount 长度的情况下增加计数。您应该在 while 循环的其他条件之前检查它。
-
chargeAccounts[17]闻起来很臭。 -
那么
len(chargeAccounts)的值是多少?
标签: python python-3.x