我正在尝试写一个程序,它引入一个文件,它要求输入一个帐号,如果它与文件上的一个数字匹配,它就会告诉用户它是有效的还是无效的。
程序会运行,但无论如何都会显示无效。怎么了?
代码如下:
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 12:34:07
acc_num[starting_index] = 0
//this sets 0 .. In the last while pass
//acc_num will value [0,0,0,0,0,0,0,0,,,,,,,]
int(acc_num[starting_index])
//This does nothing
starting_index += 1
search = int(input('Enter Account Number:'))
// Above search is set as int.
// Bellow search should be a string.
if(search in acc_num): 发布于 2015-11-24 12:35:11
def main():
try:
file = open('charge_accounts.txt','r')
search = input('Enter Account Number:')
acc_num = file.readlines()
for x in acc_num:
if search in x:
print "Yup"
file.close()
except ValueError:
print('Unable to open the file')main()
如果您正在读取文本文件,则所有内容都将作为字符串读取。" 12345“不等同于12345。首先是一个字符串。如果每一行都是一个整数,那么可以写成var = int(input(.......))(在清理了非int之后),然后与int进行比较,但对于您所描述的内容可能不是必需的。
发布于 2015-11-24 12:36:40
假设您在charge_accounts.txt中有这些帐号
12345
23456
34567
45678
56789当python执行这一行时--> acc_num = file.readlines()
acc_num将拥有以下内容:
ipdb> acc_num
['12345\n', '23456\n', '34567\n', '45678\n', '56789']为什么将列表中的第一项设置为0?
acc_num[starting_index] = 0
ipdb> acc_num
[0, '23456\n', '34567\n', '45678\n', '56789']根据mshsayem的最后一个提示:
你的列表是string,你的搜索是int。删除int()并为输入设置str。
Enter Account Number:56789
('56789', ':Yes, the account number is VALID')最后但同样重要的是,尝试使用pdb/ipdb进行调试。
https://stackoverflow.com/questions/33885310
复制相似问题