当从文件输入正确的密码和用户名时,break函数不起作用

时间:2017-11-08 20:37:14

标签: python

当我从文件中输入正确的用户名和密码时,

中断功能不起作用。 “无法获取特殊内容”这些词语无限打印。我该如何解决?如果用户输入密码/用户名错误,我希望程序重新启动。

content2=input('Username:')
content=input('Password:')

while True:
    file=open('username1.txt','r')
    data1 =file.read()
    file.close()

    file1=open('password1.txt','r')
    data2 =file1.read()
    file1.close()

    data1 = data1.split("\n")
    data2 = data2.split("\n")

    for i in range(len(data1)):
        if data1[i] == content2 and data2[i] == content:
            print('You have access to something special.')
            break
        else:
            print('Access denied.')

2 个答案:

答案 0 :(得分:2)

从最近的编辑中,我看到了你真正想要的......

请注意,我已在此处删除了第二个break,如同looping通过usernames一样,如果输入的username没有匹配,我们就不会# 39;我想立即deny,我们想继续检查......

file = open('username1.txt','r')
usernames = file.read().split("\n")
file.close()

file = open('password1.txt','r')
passwords = file.read().split("\n")
file.close()

passed = False

while not passed:
    username = input('Username:')
    password = input('Password:')
    for i in range(len(usernames)):
        if usernames[i] == username and passwords[i] == password:
            print('You have access to something special.')
            passed = True
            break
    else:
        print('Access denied. Try again')

答案 1 :(得分:1)

你可以设置一个标志来摆脱困境:

with open('username1.txt') as infile:
    data1 = infile.read().split('\n')

with open('password1.txt') as infile:
    data2 = infile.read().split('\n')

flag = True
while flag:
    content2 = input('Username:')
    content = input('Password:')

    for i in range(len(data1)):
        if data1[i] == content2 and data2[i] == content:
            print('You have access to something special.')
            flag = False
            break
        else:
            print('Access denied.')