Python
[파이썬 Python] 랜덤 함수
microsaurs
2022. 12. 5. 00:18
파이썬에서는 random 라이브러리를 사용할 수 있습니다.
from random import *
print(random()) # 0.0 ~ 1.0 미만의 임의의 값 생성
위처럼 random()를 실행하면 0.0 ~ 1.0 미만의 난수를 랜덤으로 출력해줍니다.
from random import *
print(random() * 10) # 0.0 ~ 10.0 미만의 임의의 값 생성
print(int(random() * 10) # 0 ~ 10 미만의 임의의 값 생성
print(int(random() * 10) + 1) # 1 ~ 10이하의 임의의 값 생성
random() 함수를 통해 복권 번호 자동 뽑기
print(int(random() * 45) + 1) # 1 ~ 45 이하의 임의의 값 생성
print(int(random() * 45) + 1) # 1 ~ 45 이하의 임의의 값 생성
print(int(random() * 45) + 1) # 1 ~ 45 이하의 임의의 값 생성
print(int(random() * 45) + 1) # 1 ~ 45 이하의 임의의 값 생성
print(int(random() * 45) + 1) # 1 ~ 45 이하의 임의의 값 생성
print(int(random() * 45) + 1) # 1 ~ 45 이하의 임의의 값 생성
위처럼 코드를 작성하면 1 ~ 45 사이의 숫자가 랜덤으로 6번 출력됩니다.
randrange() 함수를 사용하면 더 간편하게 랜덤 숫자를 출력할 수 있습니다.
print(randrange(1,46) # 1 ~ 46 미만의 임의의 값 생성
print(randrange(1,46) # 1 ~ 46 미만의 임의의 값 생성
print(randrange(1,46) # 1 ~ 46 미만의 임의의 값 생성
print(randrange(1,46) # 1 ~ 46 미만의 임의의 값 생성
print(randrange(1,46) # 1 ~ 46 미만의 임의의 값 생성
print(randrange(1,46) # 1 ~ 46 미만의 임의의 값 생성
randrange() 함수는 마지막 수가 포함되지 않는(미만) 함수입니다.
randint() 함수를 사용하면 시작하는 수와 마지막 수가 모두 포함됩니다.
print(randint(1,45)) # 1 ~ 45 이하의 임의의 값 생성
print(randint(1,45)) # 1 ~ 45 이하의 임의의 값 생성
print(randint(1,45)) # 1 ~ 45 이하의 임의의 값 생성
print(randint(1,45)) # 1 ~ 45 이하의 임의의 값 생성
print(randint(1,45)) # 1 ~ 45 이하의 임의의 값 생성
print(randint(1,45)) # 1 ~ 45 이하의 임의의 값 생성