需要知道如何循环

时间:2014-03-31 00:58:00

标签: python if-statement

这是我第一次在这个网站上提问,对于小错误感到抱歉。

我遇到的问题是如何将程序循环回上一行。我会更具体。在第一个else语句中,我做了它以便程序结束。我希望它允许用户再次尝试输入用户名。我该怎么做?

如果您不明白,请告诉我澄清。

usernames = ("Bob","John","Tyler","Thomas","Sanjit",
             "Super_X","Ronald","Royal_X", "Igor","KoolKid")
passwords = ("James","Smith","Jones","password","Desai",
             "asdf123","Roy","King", "Mad_man", "k00lGuy")

username = raw_input("Enter username")

if username == usernames[0] or username == usernames[1] or username == usernames[2] or \
   username == usernames[3] or username == usernames[4] or username == usernames[5] or \
   username == usernames[6] or username == usernames[7] or username == usernames[8] or \
   username == usernames[9]:
    print "  "
else:
    import sys
    sys.exit("This is not a valid username") 

password = raw_input("Enter Password:")

if username == usernames[0] and password == passwords[0] or \
   username == usernames[1] and password == passwords[1] or \
   username == usernames[2] and password == passwords[2] or \
   username == usernames[3] and password == passwords[3] or \
   username == usernames[4] and password == passwords[4] or \
   username == usernames[5] and password == passwords[6] or \
   username == usernames[6] and password == passwords[7] or \
   username == usernames[7] and password == passwords[8] or \
   username == usernames[9] and password == passwords[9]:
       print "log in successful"
else:
    import sys
    sys.exit("Username and Password do not match.")

2 个答案:

答案 0 :(得分:2)

您可以按照以下方式执行此操作:

username = ''
while username not in usernames:
    username = raw_input('Enter username: ')

如果你想给他们一定数量的尝试,你可以这样做:

username = ''
for i in range(3):  #where 3 is the number of tries
    if username not in usernames:
        username = raw_input('Enter username: ')
    else:
        break

然后你可以为密码做同样的事情。希望有所帮助。

答案 1 :(得分:0)

首先,您最好使用dict来存储这样的用户名和密码:

credentials = {
    "Bob": "James",
     # ....
}

如果您想让用户2尝试正确使用用户名:

for i in xrange(2):
    username = raw_input('Enter username: ')
    if username in credentials:
        break
else:
    print 'username not valid'

上面的代码使用python中的for..else构造来确定是否使用break来退出循环。现在,dict使检查密码是否正确变得更加容易:

if password == credentials[username]:
    print 'login successful'