모듈 Module

Jane의 study note.·2022년 10월 1일
0

파이썬 Python

목록 보기
21/31
post-thumbnail

모듈 핵심 용어

__name__ 전역변수, if__name__ == '__main__':

링크:모듈

1. 모듈

함수가 선언되어 있는 파이썬 파일

여기서 사용된 calculator.py, lottoMachine.py, reverseStr.py 와 같이 함수가 정의되어 있는 파이썬 파일

모듈이란?


# calculator.py
def add(n1, n2):
    print(f'덧셈 결과: {n1+n2}')

def sub(n1, n2):
    print(f'뺄셈 결과: {n1-n2}')

def mul(n1, n2):
    print(f'곱셈 결과: {n1*n2}')

def div(n1, n2):
    print(f'나눗셈 결과: {round(n1/n2, 2)}')
    
#module 실행.py
import random

rNum = random.randint(1, 10)
print(f'rNum: {rNum}')


import numpy

nrNum = numpy.random.randint(1, 10)
print(f'nrNum: {nrNum}')


import calculator

calculator.add(3, 4)
calculator.sub(3, 4)
calculator.mul(3, 4)
calculator.div(3, 4)

모듈 구분

실습

2문

2. 모듈 제작

import, from, as 키워드를 이용한다.

모듈 만들기

# calculator.py
def add(n1, n2):
    print(f'덧셈 결과: {n1+n2}')

def sub(n1, n2):
    print(f'뺄셈 결과: {n1-n2}')

def mul(n1, n2):
    print(f'곱셈 결과: {n1*n2}')

def div(n1, n2):
    print(f'나눗셈 결과: {round(n1/n2, 2)}')

# module 실행.py
import calculator

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

2문

# lottoMachine.py
import random

def getLottoNumbers():
    result = random.sample(range(1, 46), 6)

    return result

# module 실행.py
import lottoMachine

lottoNumbers = lottoMachine.getLottoNumbers()
print(f'lottoNumbers: {lottoNumbers}')


# reverseStr.py
def reverseStr(str):
    reversedString = ''
    for c in str:
        reversedString = c + reversedString

    return reversedString
    
# module 실행.py
import reverseStr

userInputStr = input('문자열 입력: ')
reversedString = reverseStr.reverseStr(userInputStr)
print(f'reversedString: {reversedString}')

3. 모듈 사용

import, from, as 키워드를 이용한다.

import

# calculator.py
def add(n1, n2):
    print(f'덧셈 결과: {n1+n2}')

def sub(n1, n2):
    print(f'뺄셈 결과: {n1-n2}')

def mul(n1, n2):
    print(f'곱셈 결과: {n1*n2}')

def div(n1, n2):
    print(f'나눗셈 결과: {round(n1/n2, 2)}')

# module 실행.py
import calculator

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

as

# calculator.py
def add(n1, n2):
    print(f'덧셈 결과: {n1+n2}')

def sub(n1, n2):
    print(f'뺄셈 결과: {n1-n2}')

def mul(n1, n2):
    print(f'곱셈 결과: {n1*n2}')

def div(n1, n2):
    print(f'나눗셈 결과: {round(n1/n2, 2)}')

# module 실행.py
import calculator as cal

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

#calculator.div(10, 20)

from ~ as

# calculator.py
def add(n1, n2):
    print(f'덧셈 결과: {n1+n2}')

def sub(n1, n2):
    print(f'뺄셈 결과: {n1-n2}')

def mul(n1, n2):
    print(f'곱셈 결과: {n1*n2}')

def div(n1, n2):
    print(f'나눗셈 결과: {round(n1/n2, 2)}')

# module 실행.py
from calculator import add
from calculator import sub

# from calculator import add, sub
# from calculator import *

add(10, 20)
sub(10, 20)

# mul(10, 20)

실습

# scores.py
scores = []

def addScore(s):
    scores.append(s)

def getScores():
    return scores

def getTotalScore():
    total = 0
    for s in scores:
        total += s

    return total

def getAvgScore():
    avg = getTotalScore() / len(scores)

    return avg


# module 실행.py
import scores as sc

korScore = int(input('국어 점수 입력: '))
engScore = int(input('영어 점수 입력: '))
matScore = int(input('수학 점수 입력: '))

sc.addScore(korScore)
sc.addScore(engScore)
sc.addScore(matScore)

print(sc.getScores())
print(sc.getTotalScore())
print(sc.getAvgScore())

4. 실행(메인) 파일

전역변수 __name__을 이용한 실행파일 지정.

__name__ 전역변수

# 1. addModule.py
def add(n1, n2):
    return n1 + n2

if __name__ == '__main__':
    result = add(10, 20)
    print(f'Add result: {result}')

    print(f'__name__: {__name__}')
    
# 2. subModule.py
def sub(n1, n2):
    return n1 - n2

if __name__ == '__main__':
    result = sub(10, 20)
    print(f'Sub result: {result}')

    print(f'__name__: {__name__}')
    
# 3. mulModule.py
def mul(n1, n2):
    return n1 * n2

if __name__ == '__main__':
    result = mul(10, 20)
    print(f'Mul result: {result}')

    print(f'__name__: {__name__}')
    
# 4. divModule.py
def div(n1, n2):
    return n1 / n2

if __name__ == '__main__':
    result = div(10, 20)
    print(f'Div result: {result}')

    print(f'__name__: {__name__}')
    
# 5. Module.py (module 실행.py)
import addModule as a
import subModule as s
import mulModule as m
import divModule as d

if __name__ == '__main__':
    print(f'a.add(10, 20): {a.add(10, 20)}')
    print(f's.add(10, 20): {s.sub(10, 20)}')
    print(f'm.add(10, 20): {m.mul(10, 20)}')
    print(f'd.add(10, 20): {d.div(10, 20)}')

    print(f'__name__: {__name__}')

실습

# unitConversion.py
def cmToMm(n):
    return round(n * 10, 3)

def cmToInch(n):
    return round(n * 0.393, 3)

def cmToM(n):
    return round(n * 0.01, 3)

def cmToFt(n):
    return round(n * 0.032, 3)

if __name__ == '__main__':
    print(f'10cm: {cmToMm(10)}mm')
    print(f'10cm: {cmToInch(10)}inch')
    print(f'10cm: {cmToM(10)}m')
    print(f'10cm: {cmToFt(10)}ft')

#module 실행.py
import unitConversion as uc

if __name__ == '__main__':
    inputNumber = int(input('길이(cm) 입력: '))

    returnValue = uc.cmToMm(inputNumber)
    print(f'{inputNumber}cm : {returnValue}mm')

    returnValue = uc.cmToInch(inputNumber)
    print(f'{inputNumber}cm : {returnValue}inch')

    returnValue = uc.cmToM(inputNumber)
    print(f'{inputNumber}cm : {returnValue}m')

    returnValue = uc.cmToFt(inputNumber)
    print(f'{inputNumber}cm : {returnValue}ft')

5. 패키지 (Package)

모듈을 묶어서 관리하자!

패키지

# 1. CalculatorForInt폴더 생성
# => 내부에 addCal.py, subCal.py, mulCal.py, divCal.py 파일 생성

# addCal.py
def add(n1, n2):
    return int(n1 + n2)

if __name__ == '__main__':
    print(add(3.14, 1.2))
    
# subCal.py
def sub(n1, n2):
    return int(n1 - n2)

if __name__ == '__main__':
    print(sub(3.14, 1.2))    

# mulCal.py
def mul(n1, n2):
    return int(n1 - n2)

if __name__ == '__main__':
    print(mul(3.14, 1.2))

# divCal.py
 def div(n1, n2):
    return int(n1 / n2)

if __name__ == '__main__':
    print(div(3.14, 1.2))   

# 2. CalculatorForFloat폴더 생성
# => 내부에 addCal.py, subCal.py, mulCal.py, divCal.py 파일 생성

# addCal.py
def add(n1, n2):
    return float(n1 + n2)

if __name__ == '__main__':
    print(add(3.14, 1.2))

# subCal.py
def sub(n1, n2):
    return float(n1 - n2)

if __name__ == '__main__':
    print(sub(3.14, 1.2))

# mulCal.py
def mul(n1, n2):
    return float(n1 - n2)

if __name__ == '__main__':
    print(mul(3.14, 1.2))

# divCal.py
def div(n1, n2):
    return float(n1 / n2)

if __name__ == '__main__':
    print(div(3.14, 1.2))

# 3. 두 폴더 경로에 package.py 생성

# package.py 
from CalculatorForInt import addCal
from CalculatorForInt import subCal
from CalculatorForInt import mulCal
from CalculatorForInt import divCal

returnValue = addCal.add(3.14, 0.05)
print(f'returnValue: {returnValue}')

returnValue = subCal.sub(3.14, 0.05)
print(f'returnValue: {returnValue}')

returnValue = mulCal.mul(3.14, 0.05)
print(f'returnValue: {returnValue}')

returnValue = divCal.div(3.14, 0.05)
print(f'returnValue: {returnValue}')

# package.py 
from CalculatorForFloat import addCal
from CalculatorForFloat import subCal
from CalculatorForFloat import mulCal
from CalculatorForFloat import divCal

returnValue = addCal.add(3.14, 0.05)
print(f'returnValue: {returnValue}')

returnValue = subCal.sub(3.14, 0.05)
print(f'returnValue: {returnValue}')

returnValue = mulCal.mul(3.14, 0.05)
print(f'returnValue: {returnValue}')

returnValue = divCal.div(3.14, 0.05)
print(f'returnValue: {returnValue}')




# from CalculatorForInt import addCal as ciAdd
# from CalculatorForInt import subCal as ciSub
# from CalculatorForInt import mulCal as ciMul
# from CalculatorForInt import divCal as ciDiv
from CalculatorForInt import addCal as ciAdd, subCal as ciSub, mulCal as ciMul, divCal as ciDiv

# from CalculatorForFloat import addCal
# from CalculatorForFloat import subCal
# from CalculatorForFloat import mulCal
# from CalculatorForFloat import divCal

from CalculatorForFloat import addCal, subCal, mulCal, divCal

returnValue = ciAdd.add(3.14, 0.05)
print(f'returnValue: {returnValue}')

returnValue = ciSub.sub(3.14, 0.05)
print(f'returnValue: {returnValue}')

returnValue = ciMul.mul(3.14, 0.05)
print(f'returnValue: {returnValue}')

returnValue = ciDiv.div(3.14, 0.05)
print(f'returnValue: {returnValue}')


returnValue = addCal.add(3.14, 0.05)
print(f'returnValue: {returnValue}')

returnValue = subCal.sub(3.14, 0.05)
print(f'returnValue: {returnValue}')

returnValue = mulCal.mul(3.14, 0.05)
print(f'returnValue: {returnValue}')

returnValue = divCal.div(3.14, 0.05)
print(f'returnValue: {returnValue}')

# module 실행.py

6. site-packages

어디서나 접근 가능한 패키지를 만들자!

site-packages


# module 실행.py (sitePackages.py)
import sys

for path in sys.path:
    print(path)

from calculator import cal

print(f'cal.add(10, 20): {cal.add(10, 20)}')
print(f'cal.sub(10, 20): {cal.sub(10, 20)}')
print(f'cal.mul(10, 20): {cal.mul(10, 20)}')
print(f'cal.div(10, 20): {cal.div(10, 20)}')

# calculator 폴더 아래 cal.py
def add(n1, n2):
    return n1 + n2

def sub(n1, n2):
    return n1 - n2

def mul(n1, n2):
    return n1 * n2

def div(n1, n2):
    return n1 / n2

실습

# divisor_pac 폴더 아래 divisor_mod.py 파일
def divisor(inputNumber):
    result = []
    for number in range(1, (inputNumber + 1)):
        if inputNumber % number == 0:
            result.append(number)

    return result


def prime_number(inputNumber):
    result = []
    for number in range(2, (inputNumber + 1)):
        flag = True
        for n in range(2, number):
            if number % n == 0:
                flag = False
                break

        if (flag):
            result.append(number)

    return result

# module 실행.py (sitePackages.py)
from divisor_pac import divisor_mod as dm

print(f'10의 약수: {dm.divisor(10)}')
print(f'50까지의 소수: {dm.prime_number(50)}')

7. 자주 사용하는 외부 모듈

기본적으로 알아두면 좋은 모듈

math 모듈

# 수학 관련 함수
# 합
import random

listVar = [2, 5, 3.14, 58, 10, 2]
print(f'sum(listVar): {sum(listVar)}')

# 최댓값
listVar = [2, 5, 3.14, 58, 10, 2]
print(f'max(listVar): {max(listVar)}')

# 최솟값
listVar = [2, 5, 3.14, 58, 10, 2]
print(f'min(listVar): {min(listVar)}')

# 거듭제곱
print(f'pow(13, 2): {pow(13, 2)}')
print(f'pow(13, 3): {pow(13, 3)}')
print(f'pow(13, 4): {pow(13, 4)}')

# 반올림
print(f'round(3.141592, 1): {round(3.141592, 1)}')
print(f'round(3.141592, 2): {round(3.141592, 2)}')
print(f'round(3.141592, 3): {round(3.141592, 3)}')
print(f'round(3.141592, 4): {round(3.141592, 4)}')
print(f'round(3.141592, 5): {round(3.141592, 5)}')



# math 모듈
import math

#절댓값
print(f'math.fabs(-10): {math.fabs(-10)}')
print(f'math.fabs(-0.12895): {math.fabs(-0.12895)}')

# 올림
print(f'math.ceil(5.21): {math.ceil(5.21)}')
print(f'math.ceil(-5.21): {math.ceil(-5.21)}')

# 내림
print(f'math.floor(5.21): {math.floor(5.21)}')
print(f'math.floor(-5.21): {math.floor(-5.21)}')

# 버림
print(f'math.trunc(5.21): {math.trunc(5.21)}')
print(f'math.trunc(-5.21): {math.trunc(-5.21)}')

# 최대공약수
print(f'math.gcd(14, 21): {math.gcd(14, 21)}')

# 팩토리얼
print(f'math.factorial(10): {math.factorial(10)}')

# 제곱근
print(f'math.sqrt(4): {math.sqrt(4)}')
print(f'math.sqrt(12): {math.sqrt(12)}')

random 모듈


# random 모듈

# 0이상 1미만 난수
print(f'random.random(): {random.random()}')

# 1이상 20이하 난수
print(f'random.randint(1, 20): {random.randint(1, 20)}')

# 1이상 20미만 난수
print(f'random.randrange(1, 20): {random.randrange(1, 20)}')

# 1이상 21미만 난수 5개
print(f'random.sample(range(1, 21), 5): {random.sample(range(1, 21), 5)}')

# 무작위 한개 추출
listVar = [0, 1, 2, 3, 4, 5, 6]
print(f'random.choice(listVar): {random.choice(listVar)}')

# 썩음
print(f'listVar: {listVar}')
random.shuffle(listVar)
print(f'shuffle listVar: {listVar}')

time 모듈

import time

# 시스템 시간
lt = time.localtime()
print(f'time.localtime(): {lt}')

print(f'lt.tm_year: {lt.tm_year}')
print(f'lt.tm_mon: {lt.tm_mon}')
print(f'lt.tm_mday: {lt.tm_mday}')
print(f'lt.tm_hour: {lt.tm_hour}')
print(f'lt.tm_min: {lt.tm_min}')
print(f'lt.tm_sec: {lt.tm_sec}')
print(f'lt.tm_wday: {lt.tm_wday}')

8. 외부모듈 : Flask

# 모듈을 읽어 들입니다.
from flask import Flask
from urllib import request
from bs4 import BeautifulSoup

# 웹 서버를 생성합니다.
app = Flask(__name__)
@app.route("/")

def hello():
    # urlopen() 함수로 기상청의 전국 날씨를 읽습니다.
    target = request.urlopen("http://www.kma.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=108")

    # BeautifulSoup를 사용해 웹 페이지를 분석합니다.
    soup = BeautifulSoup(target, "html.parser")

    # location 태그를 찾습니다.
    output = ""
    for location in soup.select("location"):
        # 내부의 city, wf, tmn, tmx 태그를 찾아 출력합니다.
        output += "<h3>{}</h3>".format(location.select_one("city").string)
        output += "날씨: {}<br/>".format(location.select_one("wf").string)
        output += "최저/최고 기온: {}/{}"\
            .format(\
                location.select_one("tmn").string,\
                location.select_one("tmx").string\
            )
        output += "<hr/>"
    return output

9. 외부모듈 : BeautifulSoup

# 모듈을 읽어 들입니다.
from urllib import request
from bs4 import BeautifulSoup

# urlopen() 함수로 기상청의 전국 날씨를 읽습니다.
target = request.urlopen("http://www.kma.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=108")

# BeautifulSoup을 사용해 웹 페이지를 분석합니다.
soup = BeautifulSoup(target, "html.parser")

# location 태그를 찾습니다.
for location in soup.select("location"):
    # 내부의 city, wf, tmn, tmx 태그를 찾아 출력합니다.
    print("도시:", location.select_one("city").string)
    print("날씨:", location.select_one("wf").string)
    print("최저기온:", location.select_one("tmn").string)
    print("최고기온:", location.select_one("tmx").string)
    print()

0개의 댓글