ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Python] 모듈(Module)
    Language/기초문법 2024. 5. 8. 13:22

    모듈

    : 이미 만들어진 관련된 데이터,함수를 하나로 묶은 단위

     

    파이썬모듈

    • 내부모듈 : 파이썬 설치 시 기본적으로 사용할 수 있는 모듈
    • 외부모듈 : 별도 설치 후 사용할 수 있는 모듈 ex) pandas, numpy
    • 사용자모듈 : 사용자가 직접 만든 모듈

    1. 내부모듈 

     자주사용하는 모듈)

      1. math 모듈 : 수학 관련 모듈

    import math
    #절대값
    print(f'math.fabs(-10): {math.fabs(-10)}')
    # 올림
    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(2): {math.sqrt(2)}')

     

      2. random모듈 : 난수 관련 모듈

    # 1부터 10까지 정수 중 난수 1개를 발생시켜보자.
    import random
    
    rNum = random.radint(1,10)
    print(f'rNum : {rNum}')

     

      3. time 모듈 : 시간 관련 모듈

    import time
    lt = time.localtime()
    
    # 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}')

    2. 사용자모듈

     1) 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'나눗셈결과 : {n1 / n2}')

     

     2) module.py (실행파일)

    import calculator # 만든 모듈을 임포트해서 사용
    
    calculator.add(10,20)
    calculator.sub(10,20)
    calculator.mul(10,20)
    calculator.div(10,20)

     

    AS

    import calculator as cal # as로 모듈이름을 단축해서 사용가능
    
    cal.add(10,20)
    cal.sub(10,20)
    cal.mul(10,20)
    cal.div(10,20)

     

    FROM 

    : FROM 키워드를 이용하면 모듈명이 아닌 함수명으로 사용

    # from키워드를 이용해서 모듈의 특정기능만 사용할 수 있다
    from calculator import add,sub
    from calculator import mul
    
    # 전체 키워드 가져오기
    from calculator import * 
    
    add(10,20)
    sub(10,20)
    mul(10,20)

     

    'Language > 기초문법' 카테고리의 다른 글

    [Python] 패키지(package)  (0) 2024.05.08
    [Python] __name__전역변수  (0) 2024.05.08
    [Python] 반복문 제어 (break,continue,pass)  (0) 2024.05.07
    [Python] 함수연습  (0) 2024.05.06
    [Python] 중첩함수, lamda 함수  (0) 2024.05.02
Designed by Tistory.