密码 - 登录不工作的Python

问题描述 投票:-1回答:2

我刚刚完成了Coursera的Python for Everybody 1st课程。

为了练习我的技能,我决定使用密码和用户名登录。每当我创建用户名时,我都会收到用户设置错误,其中显示“凭证无效”。这是我的代码。

import time
import datetime

print ('storingData')
print("Current date and time: ", datetime.datetime.now())
while True:
    usernames = ['Admin']
    passwords = ['Admin']

    username = input ('Please enter your username, to create one, type in create: ')

    if username == 'create':
        newname = input('Enter your chosen username: ')
        usernames.append(newname)
        newpassword = input('Please the password you would like to use: ' )
        passwords.append(newpassword)
        print ('Temporary account created')
        continue

    elif username in usernames :
        dataNum = usernames.index (username)
        cpasscode = passwords[dataNum]

    else:
        print ('Wrong credentials, please try again')
        continue

    password = input ('Please enter your password: ')

    if password == cpasscode:
        print ('Welcome ', username)

The code as it appears in my editor

python login passwords
2个回答
2
投票

在您的代码中,您已在while语句后面初始化了您的用户名数组。这意味着每次循环回到开头时,它会重新初始化,丢失之前附加的任何内容。如果将数组初始化移到循环之外,它应该按预期工作。


0
投票

这适用于python 3.对于python 2你必须采用不同的输入参考:Python 2.7 getting user input and manipulating as string without quotations

import time
import datetime

names = ['Admin']
pwds  = ['Admin']

while True:
    name = input('Name/create: ')

    if name == "create":
        name = input('New Name: ')
        pwd  = input('New Pwd : ')
        names.append(name)
        pwds.append(pwd)
        continue
    elif name in names:
        curpwdindex = names.index(name)
        print(names)
        curpwd = pwds[curpwdindex]
        givenpwd = input('Password: ')
        if givenpwd == curpwd:
            print("Welcome")
            break
        else:
            print("Inavlid Credential")
    else:
        print("Wrong Choice")
        continue
© www.soinside.com 2019 - 2024. All rights reserved.