【发布时间】:2017-11-17 15:56:36
【问题描述】:
我正在用python制作一个帐户代码,它可以工作,但它真的很长,我想知道是否有办法缩短它。这是我的代码:
user1 = "Jeff"
user2 = "Bob"
password1 = "Password"
password2 = "Lol"
username = input("Login: >> ")
password = input("Password: >> ")
if username == user1:
if password == password1:
print ("Access granted")
print ("Welcome to the system!")
home()
else:
print ("Access denied")
print ("Try again!")
print ("\n")
time.sleep(2)
login()
elif username == user2:
if password == password2:
print ("Access granted")
print ("Welcome to the system!")
home()
else:
print ("Access denied")
print ("Try again!")
print ("\n")
time.sleep(2)
login()
else:
print ("Access denied")
print ("Try again!")
print ("\n")
time.sleep(2)
login()
我创建的帐户越多,获得的时间就越长。有没有办法缩短或简化这个?
【问题讨论】:
-
你听说过定义函数吗?大多数情况下,当您重复一堆行时,最好将所有重复的代码分组到一个函数中并调用该函数。任何 python 指南都会教你如何做到这一点。
-
就像 Dijkstra 说的:“两个或更多,使用
for” -
您需要学习使用其他数据结构的列表,或者开始将内容移动到函数中。不过,这对这里来说太宽泛了。如果您的代码有效且完整,您可以将其发布在 Code Review 上,并附上良好的描述以供 UT 审查。
-
我推荐使用的设计是字典。每次有些人创建一个新帐户时,将他们的信息记录在用户字典中。然后,当有人尝试登录时,登录就像测试他们的凭据是否在您的用户字典中一样简单。
-
感谢所有帮助我编写此代码的人!我真的很感激!
标签: python python-3.x simplify