Python程序作业
我正在尝试编写一个程序,该程序引入一个文件,它要求输入一个帐号,如果它与文件上的号码匹配,它将告诉用户它是有效的还是无效的 程序运行,但无论发生什么情况,总是说无效。怎么了 代码如下:Python程序作业,python,input,Python,Input,我正在尝试编写一个程序,该程序引入一个文件,它要求输入一个帐号,如果它与文件上的号码匹配,它将告诉用户它是有效的还是无效的 程序运行,但无论发生什么情况,总是说无效。怎么了 代码如下: def main(): try: file = open('charge_accounts.txt','r') acc_num = file.readlines() starting_index = 0 w
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()
main()
如果您正在读取文本文件,则所有内容都将作为字符串读取。“12345”与12345不同。首先是字符串。如果每一行都只是一个整数,那么您可以写入var=int(输入(……)(在对非int进行清理后),然后与int进行比较,但对于您所描述的内容,这可能不是必需的。假设您负责这些账号。\u 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最后的提示:
您的列表是字符串,搜索是int。请删除int()并为您的输入设置str
Enter Account Number:56789
('56789', ':Yes, the account number is VALID')
最后但并非最不重要的是,尝试使用PDB/IPDB调试.< /P> < P>您可以考虑将程序更改为以下内容:
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”字符,并使用原始输入读取字符串,现在您的搜索比较将找到帐号 提示:
search
是一个int
,但是acc_num
是一个列表
,因此在acc_num中搜索将始终是False
。在获取input()
后,尝试删除int()
,看看会发生什么。另外,请注意acc_num
中的\n
s,这太棒了。我感谢大家的帮助。我拿出了退换货,扔掉了不需要的东西,它开始工作了。
Enter Account Number:56789
('56789', ':Yes, the account number is VALID')
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()