首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python程序作业

Python程序作业
EN

Stack Overflow用户
提问于 2015-11-24 12:10:58
回答 4查看 145关注 0票数 0

我正在尝试写一个程序,它引入一个文件,它要求输入一个帐号,如果它与文件上的一个数字匹配,它就会告诉用户它是有效的还是无效的。

程序会运行,但无论如何都会显示无效。怎么了?

代码如下:

代码语言:javascript
运行
复制
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()
EN

Stack Overflow用户

发布于 2015-11-24 13:03:46

您可以考虑将您的程序更改为以下内容:

代码语言:javascript
运行
复制
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读取字符串,现在您的搜索比较会找到帐号。

票数 0
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33885310

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档