授予Python访问权限

2024-06-02 04:28:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了这个程序,它是有效的。在

#######################################################################
## This program simulates a login screen.
## The username and passwords are stored in an input file.
#######################################################################

f=open('usernames.txt')
usernames=[]
passwords=[]

for index in range(10):
    line = f.readline().strip()
    usernames.append(line)
    line = f.readline().strip()  
    passwords.append(line)

user = input("Username: ")
found = False
for index in range(10):
     if user == usernames[index]:
         found = True
         passwrd = input("Password: ")
         if passwrd == passwords[index]:
             print("Access Granted")
         else :
             print("Username and password do not match")
         break
if (not found):
    print("Username not found")

我需要修改这个程序,使它反复要求一个有效的用户名和密码,直到访问被授予。我认为这应该很简单,我之所以有这么多麻烦是因为我不明白为什么strip()的调用需要在那里。我不明白程序如何将文本文件的索引与它后面的索引相匹配。在


Tags: andin程序forinputindexifline
1条回答
网友
1楼 · 发布于 2024-06-02 04:28:35
f = open('usernames.txt', 'r')  # you must to setup mode of opening file each time. In this case mode 'r'- read
usernames = []
granted = False

for line in f:
    # read file line by line
    usernames.append(line.strip())

if len(usernames) % 2 != 0:
    # checking that file have even numbers of lines
    print('Bad input file. Last string will be ignored')
    usernames.pop()  # removing of last string

def auth():
    user = input("Username: ")
    try:  # with try we can catch any exceptions
        index = usernames.index(user)   # check that our list have username and get index of it
        if index % 2 != 0:  # checking that it username
            print("Username not found")
            return False
    except:  # if usernames is not contained user string we catch of exception
        print("Username not found")
        return False

    passwrd = input("Password: ")
    if passwrd == usernames[index+1]:
        print("Access Granted")
        return True

    else:
        print("Username and password do not match")
        return False

while not granted:
    granted = auth()

相关问题 更多 >