2014-03-31 2 views
2

사소한 실수로 인해이 사이트에서 질문하는 것이 처음입니다.루프를 수행하는 방법을 알아야합니다.

내가 가진 질문은 프로그램을 이전 줄로 되돌려 놓는 방법입니다. 나는 더 구체적 일 것이다. 첫 번째 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

당신은 그것을 할 수 있습니다 :

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 

를 다음의 작업을 수행 할 수 있습니다

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

을 당신이 그들에게 시도의 특정 번호를 부여하려면, 당신은 할 수있다 비밀번호도 똑같습니다. 희망이 도움이됩니다.

+1

"in"의 사용법에 유의하십시오. 그것은 근본적으로 당신이 몇 번 했었던 "또는"의 긴 문자열을 작성하는 짧은 방법입니다 –

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' 

위의 코드는 break이 루프를 종료하는 데 사용되었는지 확인하기 위해 Python의 for..else 구문을 사용합니다. 이제 암호로 올바른지 확인하는 것이 훨씬 쉬워졌습니다.

if password == credentials[username]: 
    print 'login successful' 
관련 문제