我正在尝试写一个程序,它引入一个文件,它要求输入一个帐号,如果它与文件上的一个数字匹配,它就会告诉用户它是有效的还是无效的。
程序会运行,但无论如何都会显示无效。怎么了?
代码如下:
def main():
try:
file = open('charge_accounts.txt','r')
acc_num = file.readlines()
starting_index = 0
while(starting_index != len(acc_num)):
acc_num[starting_index] = 0
int(acc_num[starting_index])
starting_index += 1
search = int(input('Enter Account Number:'))
if(search in acc_num):
print(search,':Yes, the account number is VALID')
else:
print(search,':No, the account number is INVALID')
file.close()
except ValueError:
print('Unable to open the file')
main()发布于 2015-11-24 13:03:46
您可以考虑将您的程序更改为以下内容:
def main():
try:
with open('charge_accounts.txt','r') as f:
acc_num = f.read().splitlines()
starting_index = 0
while(starting_index != len(acc_num)):
search = raw_input('Enter Account Number:')
starting_index += 1
if(search in acc_num):
print(search,':Yes, the account number is VALID')
else:
print(search,':No, the account number is INVALID')
f.close()
return
except ValueError:
print('Unable to open the file')
return
main()这消除了acc_num中的'\n‘字符,并使用raw_input读取字符串,现在您的搜索比较会找到帐号。
https://stackoverflow.com/questions/33885310
复制相似问题