Python_모듈

장해수·2023년 6월 10일
  1. 모듈
  • 함수가 선언되어 있는 파이썬 파일
  1. 모듈 종류
    1) 내부 모듈
  • 파이썬에 내장되어 있는 모듈
    2) 외부 모듈
  • 별도 설치 후 사용할 수 있는 모듈
    3) 사용자 모듈
  • 사용자가 직접 만든 모듈
  1. 모듈 만들기
    (1) 모듈로 사용할 파이썬 파일 만들기

(2) 모듈을 import 하여 사용하기

  • import 모듈명 입력
  • 모듈명.기능(함수) 입력
import ex_module_calculator

ex_module_calculator.add(10, 20)
ex_module_calculator.sub(10, 20)
ex_module_calculator.mul(10, 20)
ex_module_calculator.div(10, 20)
덧셈 결과: 30
뺄셈 결과: -10
곱셈 결과: 200
나눗셈 결과: 0.5
  1. 모듈 사용
    (1) import
    (2) as 키워드
  • 모듈 이름을 단축함
import calculator as cal 

cal.add()
cal.sub()

(3) from ~ import (함수1, 함수2, ...)

  • 모듈의 특정 기능만 사용
  • 함수명만 입력해서 실행
from calculator as add
from calculator as sub

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

(4) from ~ import *

  • 모듈에 있는 모든 기능 사용
  1. 실습
    예제 1) random 모듈을 이용해서 1부터 10까지의 정수 중 난수 1개를 발생시켜 보자.
  • 코드
import random

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

예제 2) random 모듈을 이용해서 0부터 100 사이의 난수 10개를 발생시켜 보자.

  • 코드
import random

rNums = random.sample(range(0, 100), 10)
print(f'rNums: {rNums}')
  • 결과
rNums: [32, 79, 37, 65, 93, 4, 47, 23, 52, 45]

예제 3) 로또 번호 6개를 출력하는 모듈을 만들어보자.

  • 코드
#모듈 파일

import random

def getLottoNums():
    result = random.sample(range(1, 45), 6)

    return result

#실행 파일

import lottoMachine

result = lottoMachine.getLottoNums()
print(f'lotto numbers: {result}')
  • 결과
lotto numbers: [34, 35, 32, 6, 2, 5]

예제 4) 문자열을 거꾸로 반환하는 모듈을 만들어보자.

  • 코드
#모듈 파일

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

    return reversedString
    
#실행 파일

import reverseStr

userInputStr = input('문자열 입력: ')
reveredString = reverseStr.reverseStr(userInputStr)
print(f'reversedString: {reveredString}')
  • 결과
문자열 입력: 이제노 정재현 차은우 렛츠고
reversedString: 고츠렛 우은차 현재정 노제이

예제 5) 국어, 영어, 수학 점수를 입력하면 총점, 평균을 출력하는 모듈을 만들어보자.

  • 코드
#모듈 파일

scores = []

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

def getScores():
    return scores

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

    return total

def getAvgScores():
    avg = getTotalScores() / len(scores)

    return avg
    
 #실행 파일

import scores as sc

kor = int(input('국어: '))
eng = int(input('영어: '))
mat = int(input('수학: '))

sc.addScore(kor)
sc.addScore(eng)
sc.addScore(mat)

print(f'세 과목 점수: {sc.getScores()}')
print(f'총합: {sc.getTotalScores()}')
print('평균: %.2f' %sc.getAvgScores())
  • 결과
국어: 90
영어: 80
수학: 97
세 과목 점수: [90, 80, 97]
총합: 267
평균: 89.00
profile
데이터 진행시켜

0개의 댓글