RANDOM 모듈로 랜덤 숫자 얻기
random 모듈은 난수(random number)를 생성하는 데 유용한 많은 함수들을 가지고 있습니다.
randint와 choice, shuffle등이 있습니다.
randint 함수는 어떤 숫자의 범위 안에서 난수를 뽑아낸다.
>>> import random
>>> print(random.randint(1,100))
77
while루프를 사용해 간단한 숫자 맞추기 게임을 만들 때 randint를 사용할 수 있습니다.
while True:
print("Guess a number between 1 and 100")
guess=input()
i=int(guess)
if i==num:
print("right!!")
break
elif i<num:
print("더 높은 숫자")
elif i>num:
print("더 낮은 숫자")
70
더 낮은 숫자
Guess a number between 1 and 100
62
더 낮은 숫자
Guess a number between 1 and 100
61
right!!
리스트에서 항목을 무작위로 뽑기 위해 CHOICE사용하기
리스트에서 무작위로 항목을 뽑고 싶다면 choice를 사용할 수 있다.
>>> import random
>>> desserts=["ice cream", "pancakes", "brownies", "cookies", "candy"]
>>> print(random.choice(desserts))
pancakes
>>> print(random.choice(desserts))
ice cream
리스트를 섞기 위해 SHUFFLE 사용하기
shuffle 함수는 리스트에 있는 항목들을 섞어서 표출합니다.
>>> import random
>>> desserts=["ice cream", "pancakes", "brownies", "cookies", "candy"]
>>> random.shuffle(desserts)
>>> print(desserts)
['candy', 'brownies', 'cookies', 'ice cream', 'pancakes']
리스트를 출력하면 리스트가 섞여 있는 결과를 확인 할 수 있습니다.
'python' 카테고리의 다른 글
time module (0) | 2016.01.27 |
---|---|
sys module (0) | 2016.01.27 |
copy module (0) | 2016.01.27 |
파일 작업 (0) | 2016.01.27 |
내장함수 (0) | 2016.01.27 |