파이썬 비밀번호 만들기 - paisseon bimilbeonho mandeulgi

티스토리 뷰

알파벳 소문자와 숫자를 랜덤하게 조합한

6자리의 패스워드를 생성해보자.

(1) genPass() 함수를 작성한다.

(2) random 모듈의

randrange() 함수를 사용한다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

import random

def genPass():

    alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"

    password = ""

    for i in range(6):

        index = random.randrange(len(alphabet))

        password = password + alphabet[index]

    return password

print(genPass())

print(genPass())

print(genPass())

cs

  - 결과  

파이썬 비밀번호 만들기 - paisseon bimilbeonho mandeulgi

  - 설명  

alphabet에 소문자와 숫자를 

문자열로 선언한다.

password는 비워둔다.

6자리의 암호이므로

for i in range(6)로 선언하고,

index = random.randrange(len(alphabet))을 하면

index는 alphabet의 길이만큼 랜덤하게 설정된다.

이를 alphabet[index]에 넣어주면

문자열 인덱싱을 하여

alphabet의 랜덤한 한 글자를 뽑아

password에 글자를

6번 더해주는 것이다.

  + 과제  

패스워드가 적어도

하나의 숫자를 가지도록

소스를 변경하여 보자.

- 첫 번째 구상 :

반복 횟수를 구분하기

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

import random

def genPass():

    alphabet = "abcdefghijklmnopqrstuvwxyz"

    number = "0123456789"

    password = ""

    iter = random.randrange(1,7)

    for i in range(iter):

        index_n = random.randrange(len(number))

        password = password + number[index_n]

    for i in range(6 - iter):

        index_a = random.randrange(len(alphabet))

        password = password + alphabet[index_a]

    return password

print(genPass())

print(genPass())

print(genPass())

cs

  - 위와 같이 구상한 이유  

적어도 하나의 숫자를 가지면 되므로

반복 횟수 변수인 iter

random.randrange(1,7)로 설정하여

패스워드에

최소 1개 ~ 6개의 숫자가 추가되고,

영소문자는 패스워드의 개수를

6자리에서 뺀 만큼 추가하기로 하였다.

예를 들어 숫자가 4개 설정되면,

영소문자는 2개가 설정되는 것이다.

  - 결과  

파이썬 비밀번호 만들기 - paisseon bimilbeonho mandeulgi

최소 한 자리의 숫자가

패스워드에 포함되는 것은 성공했지만,

무조건 숫자가 영소문자 앞에

배치된다는 점,

연속된 숫자 / 연속된 영소문자라는

틀이 있는 데이터라는 점에서 아쉬웠다.

다른 방법을 도전!

- 두 번째 구상 :

any함수를 이용한 조건 검사

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

import random

def genPass():

    alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"

    password = ""

    for i in range(6):

        index = random.randrange(len(alphabet))

        password = password + alphabet[index]

    if any(a.isdigit() for a in password) == True:

        return password

    elif any(a.isdigit() for a in password) == False:

        return genPass()

print(genPass())

print(genPass())

print(genPass())

print(genPass())

print(genPass())

print(genPass())

cs

  - 설명  

기존의 틀은 유지하되,

for문을 다 돌고나면

any() 함수를 이용하여

숫자가 최소한 하나라도 있으면

password를 반환하고,

하나도 없으면 genPass() 함수를

다시 호출하도록 구상했다.

any() 함수는 안의 인자가 

하나라도 참이 되면 참을 반환한다.

any(a.isdigit() for a in password)는

password 안을 한 글자 씩 돌면서,

숫자가 있는지 검사한다는 것이다.

  - 결과  

(1)

파이썬 비밀번호 만들기 - paisseon bimilbeonho mandeulgi

(2)

파이썬 비밀번호 만들기 - paisseon bimilbeonho mandeulgi

(3)

파이썬 비밀번호 만들기 - paisseon bimilbeonho mandeulgi

3번의 실행 모두 정상적으로,

만족할 만한 결과가 도출되었다.

any 함수를 어떨 때 쓰면 적절할지도

생각하게 되어 좋았다.

이보다 좋은 풀이가 있는지

꼭 알고싶다.