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
答案 0 :(得分:1)
只要条件为True
,while循环就会保持循环。
count = 0
while userAccount != chargeAccounts[count] or chargeAccounts[count] == chargeAccounts[17]:
count += 1
如果我为您的计划输入了无效的userAccount
,则条件userAccount != chargeAccounts[count]
的第一部分将始终为True
。由于您使用的是True
逻辑,因此整个条件为or
。
此外,如果您想查看是否已到达列表的末尾,则不必检查最后一个列表元素(chargeAccounts[count] == chargeAccounts[17]
)的内容。请改为检查长度(count == len(chargeAccounts)
)。
要解决此问题,请将该循环条件更改为
while count < len(chargeAccounts) and userAccount != chargeAccounts[count]:
(我不确定这是否正是您所需要的,因为我并不真正遵循您的程序逻辑。但这应该会让您超越当前的错误。)
答案 1 :(得分:1)
您在字符串if chargeAccounts[index] == userAccount:
处收到错误,因为index
已经大于列表最后一个元素的索引(因为您在上面使用此index
离开了循环)。
我建议你遵循一些规则来处理列表,这些列表可以帮助你避免类似的索引错误。
for
- 循环而不是while
- 循环,如果你的线性遍历每个元素。break
醇>
所以你的代码看起来像这样:
with open('charge_accounts.txt', 'r') as infile:
chargeAccounts = infile.readlines()
for index in range(len(chargeAccounts)):
chargeAccounts[index] = chargeAccounts[index].strip()
userAccount = input("Please enter a charge account number: ")
found = False
for chargeAccount in chargeAccounts:
if chargeAccount = userAccount:
found = True
break
if found:
print("The account number", userAccount, "is in the list.")
else:
print("The account number", userAccount, "in not in the list.")