简体   繁体   English

Python-多种登录组合

[英]Python - Multiple Login Combinations

Basically, I've made a basic login program that accepts user input. 基本上,我已经制作了一个接受用户输入的基本登录程序。 But, it currently only allows one username and password combo. 但是,它目前仅允许一个用户名和密码组合。 I'm trying to make it accept multiple usernames and passwords but don't know how to. 我试图使其接受多个用户名和密码,但不知道如何。 I am new to python and I know my code is terrible/messy. 我是python的新手,我知道我的代码很糟糕/混乱。 This is what I've been trying to get it to accept multiple login combinations: 这就是我一直试图使其接受多种登录组合的方式:

output = open("logfile.txt", 'a')
login = input("please enter the correct username and password\n")
a = ("username password")("username1 password1")

if a in login:
    print("successfully logged in")
    import time
    localtime = time.asctime(time.localtime(time.time()))
    output.write("Somebody successfully logged in at ")
    output.write(localtime)
    output.write("\n")
    output.close()


else:
    print("access denied.")
    import time
    output = open("logfile.txt", "a")
    localtime = time.asctime(time.localtime(time.time()))
    output.write("Somebody unsuccessfully logged at ")
    output.write(localtime)
    output.write("\n")
    output.close()

` When I just add another 'if' block, it runs the else block aswell. `当我仅添加另一个'if'块时,它也会同时运行else块。 Also, when I just have 'a' value "username password" it works. 另外,当我只有一个“ a”值“用户名密码”时,它可以工作。 The problem is when I try to have multiple values I believe. 问题是当我尝试拥有多个我相信的价值观时。

Try 尝试

a = set(("username password","username1 password1"))
if login in a:

and it should work as you expect. 它应该可以按预期工作。

Why is left as an exercise (hint: print the value of a). 为何将其留作练习(提示:打印a的值)。

You don't want a = ("username password")("username1 password1") and if a in login: . 您不需要a = ("username password")("username1 password1")并且if a in login:

You want to set a to an iterable of some sort, the code you currently have actually produces a TypeError because you are trying to call a string (putting something in brackets doesn't make it a tuple, you need to add a trailing comma). 您想要将a设置为某种可迭代的类,当前您实际拥有的代码会产生TypeError因为您正试图调用字符串(放在方括号中的内容不会使其成为元组,您需要添加尾随逗号) 。

What you want instead is something like a = ["username password", "username1 password1"] , doe create a list with all the valid usernames and passwords. 相反,您需要的是类似a = ["username password", "username1 password1"] ,可以创建一个包含所有有效用户名和密码的列表。 You then want to check if the input - login - is in that list, so do if login in a: instead. 然后,您要检查输入- login -是否在该列表中, if login in a:则也要检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM