Skip to main content
 首页 » 编程设计

python之需要知道如何循环

2024年11月01日8dudu

这是我第一次在这个网站上提问,对于小错误,我们深表歉意。

我的问题是如何将程序循环回到上一行。我会更具体。在第一个 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.") 

请您参考如下方法:

您可以按如下方式进行:

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 

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