[Zerobase][Python Mid] 모듈

솔비·2023년 11월 28일
0

💻 Python. w/zerobase

목록 보기
8/33
post-thumbnail

파이썬중급 [모듈]

1. 모듈 (=함수가 선언되어있는 파이썬 파일)

특정기능을 가지고 있는 파이썬 파일
e.g. random.py

특징

이미 만들어진 기능으로 사용자가 쉽게 사용할 수 있다.

  • 내부모듈 : 설치 시 기본적으로 사용 할 수 있는 모듈
  • 외부모듈 : 별도 설치 후 사용 할 수 있는 모듈
  • 사용자모듈 : 사용자가 직접 만든 모듈

모듈사용법

import 모듈명
e.g. random calculator


2. 사용자모듈 만드는법

  1. 파이썬파일 만들기
  2. 해당파일에 def로 함수만들기
  3. 실행파일에서 import.파이썬파일이름
    단, 같은 폴더(Directory)에 있어야한다.

e.g. module 이라는폴더에 reverseStr 라는 함수를 만들고 실행파일에서 실행 시
(문자를 입력하면 거꾸로 출력되는 함수)

#module폴더의 reverseStr모듈
#directory : module / 파일명 : reverseStr.py

def reverseStr (str):	#함수명
    str = ''
    return str[::-1]
#실행파일에서

from module import reverseStr as r

print(r.reverseStr('python'))
# nohtyp

A. 모듈별명 : as

이때 calculator라는 모듈명이 너무 길다면,
as를 사용해서 별명으로 출력할 수 있다.

from 폴더명 import 모듈명 as 별명
from module import calculator as cal

cal.add(10,20)
cal.sub(10,20)
cal.mul(10,20)
cal.div(10,20)

B. 모듈 내 기능 별명 : from ~ as ~

파일명 사용할 필요없이 기능을 바로 사용가능하다.
from 모듈명.함수명 import 기능명

from module.reverseStr import reverseStr as r

print(r('python'))						#바로 기능 사용 가능

📁 실습

점수를 입력하면 총점과 평균을 구하는 모듈을 만들어보자

#module directory의 score.py

scores = []

def score_add(*s):
    for i in s :
        scores.append(i)

def score_get():
    return scores

def score_sum() :
    return sum(scores)

def score_avg():
    return sum(scores)  / len(scores)
#실행파일

from module import score as sc

kor = int(input('국어 점수 입력 : '))
eng = int(input('영어 점수 입력 : '))
math = int(input('수학 점수 입력 : '))

sc.score_add(kor,eng,math)
print(sc.score_get())		#[50, 80, 90]
print(sc.score_sum())		#220
print(sc.score_avg())		#73.33333333333333

3. 실행파일

실행파일의 위치를 찾고자 할때 전역변수

__name__

를 사용한다.

print(__name__)

위 코드를 출력할 때, 실행파일이라면

'__main__'

이라고 출력된다.

<예시>
만약, module파일의 score모듈에 위 코드를 코딩하고,
score파일을 import하는 실행파일에서 코드를 실행할 경우
score파일의 출력물이 실행파일에서도 출력된다.

그때, score파일의

__name__

은 'module.score'로 출력된다. (실행파일이 아니기때문)

module directory의 score.py 실행파일에서 import했을 때, module directory의 score.py의 print값이 출력

📢 모듈의 출력값이 실행파일에 출력되지 않게 하고싶다면?

if __name__ == '__main__'
	print('실행파일일 때만 출력해줘')

4.패키지 (=diretory)

한 마디로 같은 파일(directory) 안에 모듈(파일)을 모아서 관리하는것.

e.g. 위의 예시에서 사용한 모듈들을 같은 directory에 넣어놓는것

5. site-package

site-packages에 있는 모듈은 어디에서나 사용할 수 있다.
(from directory명을 해주지 않아도 됨)

📢 폴더에 구애받지 않고 사용하고싶다면
python 내 venv -> Lib -> site-packages 에 파일을 만들고 모듈을 생성하면 어드 폴더에서나 사용할 수 있다. (기본 제공 모듈[내장함수]도 모두 해당파일에 담겨있다)

📢 모듈이 어느 directory에 있는지 알고 싶다면

import sys

for path in sys.path :
    print(path)

📁 라이브러리, 패키지, 모듈의 차이점

  • 라이브러리 : 여러 패키지와 모듈을 모아놓은것
  • 패키지 : 특정 기능과 관련된 여러 모듈을 한 디렉토리안에 넣어 관리하는데 이를 패키지라고한다.
  • 모듈 : 함수, 변수, 클래스를 모아놓은 파이썬 파일

정보 출처
이미지 출처


6. 자주사용하는모듈

[수학관련 내장함수]

venv -> Lib -> site-packages에 있는 모듈

sum() : 합
max() : 최대값
min() : 최소값
pow(x,y) : x의y제곱
round(x,n) : x의 n번째까지 반올림
abs() : 절댓값

[import math]

math.fabs() : 절댓값
math.ceil() : 올림
math.floor() : 내림
math.trunc() : 버림
math.gcd(x,y) : x,y의 최대공약수
math.factorial(x) : x의 팩토리얼
math.sqrt(x) : 루트x
math.sum() :

[import time]

time.locatime() : 현재 시간정보

time.locatime().tm_year : 년
time.locatime().tm_mod : 월
time.locatime().tm_mday : 일
time.locatime().tm_hour : 시
time.locatime().tm_min : 분
time.locatime().tm_sec : 초

[import random]

random.random() : 0이상 1미만 난수
random.randrange(x,y) : x이상 y미만 난수 random.sample((범위),개수) : 범위내에서 지정개수만큼 난수생성

모듈관련해서는 추후 따로 정리하여 벨로그 업로드예정


Zero Base 데이터분석 스쿨
Daily Study Note
profile
Study Log

0개의 댓글