这是我第一次在这个网站上提问,对于一些小错误深表歉意。
我的问题是如何将程序循环回到上一行。我会更具体。在第一个 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
然后您可以对密码执行相同的操作。希望有帮助。
关于python - 需要知道如何循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22752034/