Reputation: 21
This is my first time asking a question on this site so sorry for the minor mistakes.
The question I have is how do I loop the program back to a previous line. I'll be more specific. In the first else statement I made it so that the program ends. I want it to allow the user to have another try at entering the username. How do I do that?
And If you don't understand then please ask me clarify.
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.")
Upvotes: 2
Views: 54
Reputation: 3661
First off, you'd be better off using a dict
to store username and passwords like this:
credentials = {
"Bob": "James",
# ....
}
If you want to allow the user 2 tries to get the username right:
for i in xrange(2):
username = raw_input('Enter username: ')
if username in credentials:
break
else:
print 'username not valid'
The above code uses the for..else
construct in python to determine if a break
was used to exit the loop. Now, the dict makes it much easier to check if the password was correct:
if password == credentials[username]:
print 'login successful'
Upvotes: 0
Reputation: 32189
You can do it as follows:
username = ''
while username not in usernames:
username = raw_input('Enter username: ')
If you want to give them a certain number of tries, you can do:
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
and then you can do the same thing for passwords. Hope that helps.
Upvotes: 2