함수나 변수 또는 클래스를 모아둔 파일을 모듈이라고 한다.
다른 파이썬 프로그램에서 불러와 사용할 수 있게 만든 파이썬 파일이다.
종류는 표준모듈과 외부모듈 두가지가 있다.
- 표준모듈 : 파이썬에 기본적으로 내장되어 있는 모듈
- 외부모듈 : 다른 사람들이 만들어서 공개한 모듈
모듈 사용방법
- import 모듈
- from 모듈 import 함수
- from 모듈 import 함수1, 함수2
- from 모듈 import *
외부모듈 사용하기
먼저 모듈로 사용할 파일을 만들어준다.
# add_sub_module.py 파일을 만듦
def add(a, b):
return a + b
def sub(a, b):
return a - b
이후 다른 파일에서 방금 생성한 파일을 임포트해서 사용한다.
# 방식1
import add_sub_module
print(add_sub_module.add(3, 4))
# 결과값
# 7
print(add_sub_module.sub(4, 2))
# 결과값
# 2
# 방식2
from add_sub_module import add, sub
print(add(3, 4))
# 결과값
# 7
print(sub(4, 3))
# 결과값
# 1
print(add)
# 결과값
# <function add at 0x7fe980c481f0>
converter 파일 생성하기
MILES = 0.621371
POUND = 0.00220462
def kilometer_to_miles(kilometer):
return kilometer * MILES
def gram_to_pounds(gram):
return gram * POUND
converter 파일을 import 하기
import converter
miles = converter.kilometer_to_miles(160)
print(f"160km = {miles}miles")
# 결과값
# 160km = 99.41936miles
pounds = converter.gram_to_pounds(1000)
print(f"1000g = {pounds}pounds")
# 결과값
# 1000g = 2.20462pounds
from converter import *
miles = kilometer_to_miles(140)
print(miles)
# 결과값
# 86.99194
pounds = gram_to_pounds(100)
print(pounds)
# 결과값
# 0.220462
import 별칭 붙여 사용하기
# converter 라는 이름을 cvt 로 사용한다
import converter as cvt
miles = cvt.kilometer_to_miles(150)
print(miles)
# 결과값
# 93.20565
pounds = cvt.gram_to_pounds(1000)
print(pounds)
# 결과값
# 2.20462
# converter 파일에서 kilometer_to_miles 메서드를 k2m 으로 불러서 사용하겠다는 의미이다.
from converter import kilometer_to_miles as k2m
miles = k2m(160)
print(miles)
# 결과값
# 99.41936
표준모듈 사용하기
파이썬에 기본적으로 설치되어 있는 모듈로 별도의 설치 없이 import 를 사용할 수 있다.
1. math
수학과 관련되 값과 함수를 제공한다.
# 원주율
print(math.pi)
# 결과값
# 3.141592653589793
# 올림과 내림
print(math.ceil(1.1)) # 올림
print(math.floor(1.9)) # 내림
# 결과값
# 2
# 1
# 절사와 내림과는 다름
# 내림 : 해당 숫자보다 작은 숫자를 찾는것
# 절사 : 소수점을 잘라내는것
# 소수점 이하 절사
print(math.trunc(-1.9)) # 절사
print(math.floor(-1.9)) # 내림
# 결과값
# -1
# -2
# 제곱근
math.sqrt(25) # 루트 25
# 결과값
# 5
# 제곱
math.pow(2, 3) # 2 ** 3
# 결과값
# 8.0
2. random
난수를 생성하는 모듈이다.
import random
# randint()
# 전달하는 두 인수 사이의 정수를 임의로 생성
# 1에서 10 까지의 임의로 생성한 정수값
random.randint(1, 10)
# randrange()
# 특정 범위에 속한 정수 중에서 하나를 임의로 생성
# 마지막 숫자보다 1이 작음 ( 리스트로 생성해서 한개를 랜덤으로 뽑는것이기 때문에)
random.randrange(10)
# random()
# 0 이상 1 미만의 범위에서 임의의 실수를 생성
# 0% 이상 100% 미만으로 확률을 처리할 때도 사용한다.
random.random()
# choice()
# 전달된 시퀀스 자료형에 속한 요소 중에서 하나를 임의로 반환
seasons = ["spring", "summer", "fall", "winter"]
random.choice(seasons)
# sample()
# 전달된 시퀀스 자료형에 속한 요소 중에서 지정된 개수의 요소를 임의로 반환
# 반환 결과는 리스트 자료형
# 중복 없이 선택 된다.
random.sample(range(1, 46), 6)
# 결과값
# [4, 21, 43, 44, 10, 39]
# shuffle()
# 임의로 섞는 것
# 전달된 시퀀스 자료형에 속한 요소의 순서를 임의로 조정하여 다시 재배치
# 실제로 전달된 시퀀스 자료형의 순서가 재배치 된다
# str 이나 튜플 자료형을 전달하면 에러가 발생한다
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list)
# 결과값
# [4, 3, 5, 2, 1]
3. time
시간처리와 관련된 모듈이다.
import time
# time()
# 1970년 1월 1일 0시 0분 0초부터 현재까지 경과된 시간을 반환(UNIX OS 배포 날짜)
# 소수점 이하는 마이크로초를 의미
time.time()
# 결과값
# 1682580766.715432
# ctime()
# 인수로 전달된 시간을 형식에 맞춰서 반환
time.ctime(time.time())
# 결과값
# 'Thu Apr 27 16:33:50 2023'
# sleep()
# 인수로 전달된 초 만큼 일시 정지
time.sleep(1) # 1초간 일시정지
s = time.time()
time.sleep(1)
print(time.time() - s)
# 결과값
# 1.005573034286499
4. datetime
날짜와 시간 데이터를 처리하는 모듈이다.
import datetime
# now()
# 시스템의 현재 날짜와 시간을 반환
print(datetime.datetime.now())
# 결과값
# 2023-04-27 16:40:35.775238
# date()
# 특정 날짜를 만들어서 반환
print(datetime.date(2014, 8, 25))
# 결과값
# 2014-08-25
# time()
# 특정 시간을 만들어서 반환
print(datetime.time(10, 48, 0))
# 결과값
# 10:48:00
# 날짜/시간 관련 필드값
# today = datetime.datetime.now()
print(today.year)
# 결과값
# 2023
print(today.month)
# 결과값
# 4
print(today.day)
# 결과값
# 27
print(today.minute)
# 결과값
# 44
print(today.second)
# 결과값
# 31
# timedelta()
# 날짜/시간 데이터의 연산을 위해 사용한다
today = datetime.datetime.now()
yesterday = today - datetime.timedelta(days = 1)
tomorrow = today + datetime.timedelta(days = 1)
print(yesterday)
print(tomorrow)
# 결과값
# 2023-04-26 16:49:03.412061
# 2023-04-28 16:49:03.412061
패키지
모듈의 집합으로 모듈은 기본적으로 패키지의 형태로 배포된다.
파이썬에서 기본적으로 제공하지 않는 외부에서 만들어진 패키지를 외부모듈 이라고 한다.
패키지 관리자
패키지의 추가나 삭제와 같은 작업을 수행하기 위해 사용한다.
패키지 관리자의 종류
- pip
- conda
설치 명령어
pip(conda) install (package)
삭제 명령어
pip(conda) uninstall (package)
numpy 모듈 설치

import numpy as np
np.sum([1, 2, 3, 4, 5])
# 결과값
# 15