2011-08-06 6 views
1

로그인을 만들려고합니다.파이썬 : 일치하는 사용자 이름/암호; 올바르지 않은 경우 암호를 묻는 메시지가 표시됩니다.

사용자 이름과 비밀번호의 라이브러리를 생성/가져 오는 방법을 잘 모르겠습니다. 나는 현재 답변을 찾기 위해 연구 중이지만 어느 쪽이든 물어 보았습니다. 암호와

일치하는 사용자 이름 // (부분적으로 해결; 일치하는 비밀번호로 여러 사용자 이름을 추가 할 필요) 암호가 잘못된 경우

어떻게 루프를 만들? 올바르지 않은 암호를 입력하면 암호를 다시 입력하라는 메시지가 나타납니다. // (해결은, 사용 [인쇄] 대신 [수익])

암호 시도의 특정 번호로 루프를 제한하는 방법. 다음은

내가 시도 것입니다 :

def check_password(user, password): 
""" Return True if the user/pass combo is valid and False otherwise. """ 

# Code to lookup users and passwords goes here. Since the question 
# was only about how to do a while loop, we have hardcoded usernames 
# and passwords. 
return user == "pi" and password == "123" 

데프 로그인() : 는 "" "사용자 이름과 암호 확인, 그것은 작동 될 때까지 반복 반환 진정한 경우에만 성공 .." ""

테스트를 위해
try: 
    while True: 
     username = raw_input('username:') 
     password = raw_input('password:') 
     if check_password(username, password): 
      break 
     else: 
      print "Please try again" 

    print "Access granted" 
    return True 
except: 
    return False 

로그인()

잘못된 암호. * 'print'대신 'return'을 사용하기 때문에 루프의 고정 된 부족이 프롬프트됩니다. 그리고 '만약'대신 '동안

def login(): 
#create login that knows all available user names and match to password ; if password is incorect returns try again and propmts for password again# 
username = raw_input('username:') 
if username !='pi': 
    #here is where I would need to import library of users and only accept those usernames; needs to be like 'pi' or 'bob' or 'tim'etc. 
    print'user not found' 
    username = raw_input('username') 
password = raw_input('password:') 
#how to match password with user? store in library ? 
while password != '123': 
    print 'please try again' # You have to change the 'return' to 'print' here 
    password = raw_input('password')   
return 'access granted' 
#basically need to create loop saying 'try again' and prompting for password again; maybe smarter to ask limited number of 
#times before returning 'you have reached limit of attempts# 
if password == '123': 
    #again matching of passwords and users is required somehow 
    return 'access granted' 

로그인() 이름 : wronguser 사용자가 usernamepi에게 비밀번호를 찾을 수 없습니다 wrongpass 다시 password123 시도하십시오' '

을 액세스 부여
Merigrim : 덕분에 업데이트하기 전에210

#first 시도 데프 로그인() :

>>> login() 
username:pi 
password:123 
'access granted' 
>>> login() 
username:pi 
password:wrongpass 
'please try again' 

내가 암호를 다시 묻는 메시지를 표시하도록 루프를 작성해야합니다 : 여기

# Create login that knows all available user names and match to password; 
    # if password is incorect returns try again and propmts for password again# 
    username = raw_input('username:') 
    if username !='pi': 
     # Here is where I would need to import library of users and only 
     # accept those usernames; needs to be like 'pi' or 'bob' or 'tim'etc. 
     return 'user not found' 

    password = raw_input('password:') 

    # How to match password with user? store in library? 
    if password != '123': 
     return 'please try again' 

    password = raw_input('password:') 
    if password != '123': 
     return 'please try again' 

    # Basically need to create loop saying 'try again' and prompting 
    # for password again; maybe smarter to ask limited number of 
    # times before returning 'you have reached limit of attempts 

    elif password == '123': 
     # Again matching of passwords and users is required somehow 
     return 'access granted' 

은 현재 어떻게 작동 . 당신이 원하는 무엇

답변

2

while 문입니다.이 같은

대신 중첩 IF-문 : 당신은이 작업을 수행 할 수

if password != '123': 
    return 'please try again' 
    password = raw_input('password:') 
    if password != '123': 
     return 'please try again' 
elif password == '123': 
    return 'access granted' 

:

while password != '123': 
    print 'please try again' # You have to change the 'return' to 'print' here 
    password = raw_input('password:') 
return 'access granted' 

올바른 암호를 입력 할 때까지이 사용자에게 암호를하라는 것입니다. while 문에 더 익숙해지기를 원하면 this one과 같은 자습서를 확인하는 것이 좋습니다. 무언가를 반환하면 함수가 그곳에서 종료되므로 사용자는 절대로 암호를 묻지 않습니다. 위의 코드에서 반환 값을 print 문으로 변경했습니다.

+0

고맙습니다. 지금 귀하의 링크를 읽고 있습니다. 그리고 네, 잘못 입력하면 암호를 묻는 메시지가 나타나지 않는 것 같습니다. – PythagorasPi

1

여기에는 사용자 이름과 암호가 포함되어있는 또 다른 솔루션이 있으며 누군가가 입력을 중단하려고하는 경우 예외 처리기가 있습니다.

크래커에게 유효한 사용자 이름이 무엇인지 알 수 없도록 사용자와 비밀번호를 함께 사용하는 것이 가장 좋습니다.

def check_password(user, password): 
    """ Return True if the user/pass combo is valid and False otherwise. """ 

    # Code to lookup users and passwords goes here. Since the question 
    # was only about how to do a while loop, we have hardcoded usernames 
    # and passwords. 
    return user == "pi" and password == "123" 

def login(): 
    """ Prompt for username and password, repeatedly until it works. 
    Return True only if successful. 
    """ 

    try: 
     while True: 
      username = raw_input('username:') 
      password = raw_input('password:') 
      if check_password(username, password): 
       break 
      else: 
       print "Please try again" 

     print "Access granted" 
     return True 
    except: 
     return False 

# For testing 
login() 
+0

예 예 예 !! 그 점에 대해 정말 고마워. 마지막 답변에서 'if'대신 'while'에 대해 배우기 시작했습니다. – PythagorasPi

관련 문제