728x90
모듈이란
- 함수나 변수 또는 클래스를 모아 둔 파일
- 다른 파이썬 프로그램에서 불러와 사용할 수 있게 만든 파이썬 파일
- 종류
- 표준 모듈: 파이썬에 기본적으로 내장되어 있는 모듈
- 외부 모듈: 다른 사람들이 만들어서 공개한 모듈
모듈 사용
- import 모듈
- from 모듈 import 함수1, 함수2
- from 모듈 import *
import add_sub_module
print(add_sub_module.add(3, 4))
7
print(add_sub_module.sub(4, 2))
2
from add_sub_module import add, sub
add(3, 4)
7
add
<function add_sub_module.add(a, b)>
sub(4, 3)
1
-----
같은 디렉토리에 「converter.py」를 작성
MILES = 0.621371
POUND = 0.00220462
def kilometer_to_miles(kilometer) :
return kilometer * MILES
def gram_to_pounds(gram) :
return gram * POUND
-----
import converter
miles = converter.kilometer_to_miles(160)
print(miles)
99.41936
pounds = converter.gram_to_pounds(1000)
print(pounds)
2.20462
from converter import *
miles = kilometer_to_miles(140)
print(miles)
86.99194
pounds = gram_to_pounds(100)
print(pounds)
0.220462
별명 사용하기
import converter as cvt
miles = cvt.kilometer_to_miles(150)
print(miles)
93.20565
from converter import kilometer_to_miles as k2m
miles = k2m(150)
print(miles)
93.20565
표준 모듈
- 파이썬에 기본적으로 설치되어 있는 모듈
- 별도의 설치 없이 import 사용 가능
math
- 수학과 관련된 값과 함수를 제공
import math
# 원주율
print(math.pi)
# 올림과 내림
print(math.ceil(1.1)) # 올림
print(math.floor(1.9)) # 내림
2
1
# 소수점 이하 절사
print(math.trunc(-1.9)) #절사
print(math.floor(-1.9)) #내림
-1
-2
# 제곱근
print(math.sqrt(25)) # 루트 25
5.0
random
- 난수 생성 모듈
import random
- randint()
- 전달하는 두 인수 사이의 정수를 임의로 생성
random.randint(1,10)
7
- randrange()
- 특정 범위에 속한 정수 중에서 하나를 임의로 생성
random.randrange(1, 10, 2)
5
- random()
- 0이상 1미만 범위에서 임의의 실수를 생성
- 0% 이상 100% 미만으로 확률을 처리할 때도 사용
random.random()
0.09057776665470796
# 50% 확률로 안녕하세요를 출력하는 코드
if random.random() < 0.5:
print("안녕하세요")
안녕하세요
- choice()
- 전달된 시퀀스 자료형에 속한 요소 중에서 하나를 임의로 반환
seasons = ["spring", "summer", "fall", "winter"]
random.choice(seasons)
'winter'
- sample()
- 전달된 시퀀스 자료형에 속한 요소 중 지정된 개수의 요소를 임의로 반환
- 반환 결과는 리스트 자료형
- 중복 없이 선택
random.sample(range(1, 46), 6)
[14, 23, 28, 17, 38, 13]
sorted(random.sample(range(1, 46), 6))
[15, 18, 21, 32, 33, 40]
- shuffle()
- 임의로 섞는 것
- 전달된 시퀀스 자료형에 속한 요소의 순서를 임의로 조정하여 다시 재배치
- 실제로 전달된 시퀀스 자료형의 순서가 재배치됨
- str이나 튜플 자료형을 전달하면 에러
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list)
[3, 2, 4, 5, 1]
time
- 시간처리와 관련된 모듈
import time
- time()
- 1970년 1월 1일 0시 0분 0초부터 현재까지 경과된 시간을 반환(UNIX OS 배포 날짜)
- 소수점이하는 마이크로초를 의미
print(time.time())
1736757699.9262242
- sleep()
- 인수로 전달된 초 만큼 일시 정지
# 3초간 일시 정지
time.sleep(3)
s = time.time()
#실행문
time.sleep(1)
print(time.time() - s)
1.0101532936096191
패키지
- 모듈의 집합
- 모율은 기본적으로 패키지의 형캐로 배포됨
- 파이썬에서 기본적으로 제공하지 않는, 외부에서 만들어진 패키지를 외부 모듈 이라고 함
패키지 관리자
- 패키지의 추가나 삭제와 같은 작업을 수행하기 위해 사용(둘중 하나를 골라서 사용 pip를 주로 사용(짧아서)))
- pip
- conda
- 설치 명령어
- pip install (package)
- conda install (package)
- 삭제 명령어
- pip uninstall (package)
- conda uninstall (package)
728x90