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
发布于 2017-12-01 14:51:02
只要时间循环的条件是True
,它就会一直循环。
count = 0
while userAccount != chargeAccounts[count] or chargeAccounts[count] == chargeAccounts[17]:
count += 1
如果我向您的程序输入无效的userAccount
,条件userAccount != chargeAccounts[count]
的第一部分将始终是True
。这使得整个条件都是True
,因为您使用的是or
逻辑。
此外,如果要检查是否已到达列表的末尾,则不必检查最后一个list元素(chargeAccounts[count] == chargeAccounts[17]
)的内容。检查长度(count == len(chargeAccounts)
)。
若要修复此问题,请将该循环条件更改为
while count < len(chargeAccounts) and userAccount != chargeAccounts[count]:
(我不确定这是否正是你所需要的,因为我并没有真正遵循你程序的逻辑。不过,这应该可以让您通过当前的错误。)
发布于 2017-12-01 15:05:45
您在字符串if chargeAccounts[index] == userAccount:
处得到错误,因为index
已经大于列表中最后一个元素的索引(因为您在上面的index
中留下了这个循环)。
我建议您遵循一些规则来处理列表,这样可以避免与索引类似的错误。
for
-loop而不是while
-loop。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.")
https://stackoverflow.com/questions/47595771
复制相似问题