모듈이란?
-여러 기능들이 뭉쳐진 하나의 .py 파일 (다른 파일에서 import하여 사용 가능!)
-코드를 분리, 공유!
-함수, 클래스, 변수 등 Python 코드가 저장된 파일
-표준 모듈: Python 기본 내장
-외부 모듈: 직접 만든 모듈
-모듈은 단순 .py 파일을 만들면 생성!
-모듈을 불러올 때 파일명에서 .py를 생략!
-import 할 파일들은 같은 폴더에 위치해야 한다!
<모듈 코드 예시 - calc.py>
# 계산기
def add(a,b):
return a + b
def sub(a,b):
return a - b
def multiply(a,b):
return a * b
def divide(a,b):
return a / b
import 모듈이름
-import calc : calc.add(10, 20)
-import calc as a : a.add(10, 20)
from 모듈이름 import 시퀀스명
-from calc import add : add(10, 20)
-from calc import add as a : a(10, 20)
-from calc import add, sub : sub(10, 20)
-from calc import * : 시퀀스 전부 import
<자주 쓰이는 모듈들>
| 모듈 이름 | 모듈 설명 |
|---|---|
| datetime | 날짜와 시간의 조작 및 형식화를 제공하는 모듈 |
| time | 시간 측정, 대기 및 시스템 시간 관련 기능을 제공하는 모듈 |
| math | 수학적 계산을 위한 함수와 상수를 제공하는 모듈 |
| random | 난수 생성 및 무작위 작업을 지원하는 모듈 |
| sys | Python 인터프리터와 관련된 정보 및 명령행 인수 처리를 지원하는 모듈 |
| os | 운영 체제와 상호작용하며 파일 시스템 조작 및 환경 변수 접근을 지원하는 모듈 |
| json | JSON 데이터를 파싱하거나 Python 객체로 변환하는 기능을 제공하는 모듈 |
<datetime 모듈 활용 예시 코드1>
from datetime import datetime, timedelta, timezone
now = datetime.today()
print(now) # 2024-12-12 23:15:54.305579
print(now.year) # 2024
print(now.month) # 12
print(now.day) # 12
print(now.hour) # 23
print(now.minute) # 15
print(now.second) #54
print(f"{now.year}년 {now.month}월 {now.day}일")
#2024년 12월 12일
now = datetime.now() #얘는 타임존 있음 UTC +9
print(now)
# datetime.today()와 datetime.now() 거의 똑같은 역할!
#2024-12-12 23:15:54.312562
#특정 날짜 계산
next_week = now + timedelta(weeks = 1, hours = 1)
print(next_week)
#2024-12-20 00:15:54.312562
# 타임존 계산
print(timezone.utc) # UTC
print(datetime.now(timezone.utc))
#2024-12-12 14:15:54.313557+00:00
print(datetime.now(timezone(timedelta(hours = 9))))
#2024-12-12 23:15:54.316552+09:00
<datetime 모듈 활용 예시 코드2>
from datetime import date
open_day = date(year = 2024, month= 11, day=18) #수업 시작한 날
print(date.today()) # 2024-12-12
print(date.today().weekday()) # 3 출력, 오늘은 목요일이니까!
week = ["월", "화", "수", "목", "금", "토", "일"]
print(week[date.today().weekday()]) #목 출력
pass_day = date.today() - open_day
print(pass_day.days) #경과 일수인 24일 출력
<time 모듈 활용 코드 예시>
import time
print(time.time())
# 1734019970.2189918
#1970년 1월 1일 0시 0분 0초(UTC) 부터 현재까지의 경과시간을 초 단위로 반환
print(time.localtime())
#time.struct_time(tm_year=2024, tm_mon=12, tm_mday=13, tm_hour=1, tm_min=12, tm_sec=50, tm_wday=4, tm_yday=348, tm_isdst=0)
#tm_wday는 숫자 범위 [0,6], 요일
#tm_yday는 숫자 범위 [0, 366]
#tm_isdst는 summer time 적용 중이면 1, 아니면 0, 알 수 없으면 -1
print("2초 대기")
time.sleep(2)
print("대기 완료") #잠깐 멈추게 하기
start = time.perf_counter() #시간 측정
time.sleep(1)
end = time.perf_counter()
print(end - start) #1.000509299999976
<math 모듈 활용 코드 예시>
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(25)) #제곱근, 5.0
print(math.factorial(5)) #팩토리얼 계산, 120
print(math.ceil(2.43)) #올림, 3
print(math.floor(4.88)) #버림, 4
print(round(2.51)) #반올림, 3
<random 모듈 활용 예시>
import random
import math
print(random.randint(1000, 9999)) # random int 1000 이상 9999 이하의 난수 생성
print(random.uniform(1.1, 5.5)) #1.1 이상 5.5 이하의 실수 중 난수 생성
print(random.random()) #0.0과 1.0 사이의 실수 중 난수값을 리턴
#randrange(start, stop, step): start이상 stop 미만의 정수 중 난수 값 리턴
print(random.randrange(1000, 10000))
#매개변수로 시퀀스 타입(문자열, 튜플, 리스트)을 받고, 그중에서 무작위로 하나를 선택하여 리턴
choices = [1, 2, 3, 4, 5, 6, 7, 8]
print(random.choice(choices))
rand = 1000 + math.floor(random.random() * 9000) # 4자리의 난수 생성 (다른 언어에서 난수 생성 할 때 자주 사용하는 방식)
print(rand)
-1~45까지의 수 중에서 랜덤으로 6개의 숫자를 뽑는다.
-6개의 숫자 중 중복되는 숫자는 없도록 한다.
-오름차순으로 정렬한다.
<실습. 로또 뽑기 코드 예시>
import random
#방법1
choices = list(range(1, 46))
#print(choices)
pick = []
for i in range(6):
choice = random.choice(choices)
pick.append(choice)
choices.remove(choice)
pick.sort() #오름차순으로 뽑은 숫자들 정렬
print(pick)
#방법2
lotto = random.sample(range(1, 46), 6) #sample(arr, 개수) 샘플링
print(sorted(lotto))
#방법3
lotto = set()
while len(lotto) < 6:
lotto.add(random.randint(1, 45))
print(sorted(lotto))
<sys 모듈 활용 예시 코드>
import sys
#명령행 인수 출력
print(sys.argv)
print(sys.argv[1:])
if "-h" in sys.argv or "--help" in sys.argv:
print("사용법: python main.py [옵션]")
print("-h, --help 도움말 표시")
print("-v, --version 버전 정보 표시")
sys.exit(0) # 프로그램 종료
if "-v" in sys.argv or "--version" in sys.argv:
print("버전 : 1.0.0")
sys.exit(0)
실행하는 파일명 뒤로 -h, --help 를 덧붙이면 도움말을,
-v나 --version을 붙이면 버전을 출력해준다.
<os 모듈 활용 코드 예시>
import os
dir_current = os.getcwd() #현재 위치 나타내기
print('현재 위치: ',dir_current)
file_path = os.chdir(dir_current) #이 경로로 이동
dir = os.popen('ls') #해당 폴더에 와서 ls로 조회
print(dir.read()) #조회한 내용 읽어들이기
os.mkdir("test") #test라는 폴더 생성하기
print(('디렉토리 생성: test'))
os.rmdir("test")
print(('디렉토리 삭제: test'))
#환경 변수 확인
print('PATH 환경 변수: ', os.environ.get('PATH'))
<json 모듈 활용 코드 예시>
import json
#파이썬 객체 -> JSON 문자열 변환
data = {
"name": "홍길동",
"age": 20,
"city": "서울"
} #딕셔너리
json_str = json.dumps(data) #json 문자열로 변환
print(json_str)
#출력 결과: {"name": "\ud64d\uae38\ub3d9", "age": 20, "city": "\uc11c\uc6b8"}
json_obj = json.loads(json_str) #파이썬 객체로 다시 변환
print(json_obj, json_obj["name"])
#출력 결과: {'name': '홍길동', 'age': 20, 'city': '서울'} 홍길동
이외에도 파이썬 커뮤니티에서 제공하는 다양한 모듈을 설치해서 사용할 수 있다.
<설치 명령어>
-conda install 모듈명 : anaconda에서 지원을 받는 패키지만을 관리하는 관리자
-pip install 모듈명 : python의 정식 지원을 받는 패키지만을 관리하는 관리자 (주피터 노트북에서 해당 명령어를 사용할 때는 명령어 앞에 !를 붙일 것!)
-> 혼용하면 conda update, install, uninstall 등을 할 때 일부 패키지가 누락되거나 같은 버전이 두 개 설치된 것처럼 보이는 문제가 발생할 수 있다. 보통은 pip를 더 자주 쓰기도 한다.
=> 보통은 패키지를 설치할 때 base에 설치하지 않고 가상환경에 설치하는 것을 추천하기도 한다. 이는 프로젝트마다 요구하는 패키지의 버전이 다를 수 있기 때문이다.
<영어 타자 연습 프로그램>
<영어 타자 연습 게임 코드 예시>
#실습. 타자연습
import random
import time
#테스트할 단어 리스트
words = ["mountain", "river", "forest", "ocean", "desert", "tree", "flower", "cloud", "rain", "sunlight"]
def game(): #게임 프로그램을 함수화 하기
print("영어 타자 연습 게임")
print("게임종료를 원하시면 exit를 입력하세요")
total_words = 0
start_time = time.time()
while True: #무한 반복
word = random.choice(words) #랜덤으로 단어 하나 고르기
print(f"단어: {word}")
while True: #무한 반복
user_input = input("입력: ")
if user_input == "exit": #exit 입력하면 게임 종료하기
end_time = time.time()
total_time = end_time - start_time
print("\n게임종료")
print(f"총입력한 단어는 {total_words}개입니다.")
print(f"총걸린 시간은 {total_time:.2f}초")
print(f"단어당 평균시간은 {total_time / total_words:.2f}초")
return #전체 함수 종료하라는 의미
if user_input == word:
print("통과")
total_words += 1
break
else:
print("오타! 다시입력")
game()
이 코드는 랜덤으로 단어를 하나 고르는 거라서 중복된 단어가 뜰 수도 있다는 점이 조금 아쉬운 것 같다. 나중에 수정해봐야지.