반응형

파이썬에 있는 random 모듈에 대해 알아보고자 한다.


random을 쓰는 곳은 일반적으로 파이썬 공부를 할 때는 많이 없겠지만, 


다양한 프로젝트, 난수 생성이 필요한 프로그램, 게임 제작 등등에서는 아주 많이 쓰이게 된다.


이제 random 모듈을 이용해보자.




random 모듈 호출


import random



random 모듈 내부 함수는 3가지 정도를 알아보려 한다.

참고로 random 모듈에는 다양한 함수(객체)가 존재한다.




random 모듈 내의 함수 3가지 


random() :: float형 난수를 생성해준다.


randint(a,b) :: a <= x <= b인 난수 x를 생성해준다.


randrange(a,b) :: a <= x < b인 난수 x를 생성해준다.


바로 적용에 들어가보자.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import random
 
for i in range(5):
    print('random.random() :: ', random.random())
print('\n')
 
for i in range(5):
    print('int(random.random()*100) :: 'int(random.random()*100))
print('\n')
 
for i in range(5):
    print('random.randint(1,10) :: ', random.randint(1,10))
print('\n')
 
for i in range(5):
    print('random.randrange(1,11) :: ', random.randrange(1,11))
 
//                                                       This source code Copyright belongs to Crocus
//                                                        If you want to see more? click here >>
cs




여기서 볼 수 있는 것은

random.random()을 이용하여 다양한 난수를 만들 수 있다는 것이다.


int(random.random()*100) 라고 쓰면 결국 0~99의 난수를 생성 할 수 있게 되는 것이다.


0.0022300

0.0234123

0.9999999가 있다면 *100을 하면 각각 0, 2, 99의 난수들이 생성된다.

















반응형