모듈 : 함수, 변수, 클래스를 모아 놓은 파일. 즉, 다른 python 프로그램에서 호출하여 사용할 수 있게끔 만든 파이썬 파일.

 

1. from 

2. import

 

모듈 만들기

%%writefile test_module.py

# file name : test_module.py


def add(a, b):
    return a + b

def sub(a, b):
    return a - b

def mul(a, b):
    return a * b

def div(a, b):
    return a / b

 

모듈 불러오기

import test_module

 

모듈 안에 있는 함수만 불러오고 싶을 때

from test_module import add
from test_module import sub
from test_module import mul
from test_module import div

from test_module import add, sub, mul, div

print(add(1,2), sub(3,4), mul(5,6), div(7,8))

 

3. if __name__ == "__main__": 의 의미

 

.py 파일에는 __name__을 변수로 가짐.

이 변수는 모듈의 이름을 가지고 있는 변수. 현재 .py 파일의 이름을 가지고 있는 변수라는 의미

예를 들어, test_module.py라면 test_module 이라는 문자열을 name변수가 가지고 있게 됨.

__name__변수는 파이썬이 내부적으로 사용하는 특별한 변수 이름.

만약 명령창에서 python test_module.py처럼 직접 test_module.py파일을 실행할 경우 __name__ 변수에는 

"__main__"값이 저장됨.

 

__name__이 정확하게 무엇을 의미하는지 알기 위해서 아래와 같이 파일을 만들고 실행을 해봄.

 

모듈 만들기

%%writefile test_module2.py

print('hello 모듈 시작')
print('hello.py __name__:', __name__)    # __name__ 변수 출력
print('hello 모듈 끝')
import test_module2  # test_module 모듈을 가져오고

print('main.py __name__:' , __name__) # __name__ 변수 출력

실행결과

hello 모듈 시작
hello.py __name__: test_module2
hello 모듈 끝
main.py __name__: __main__

파이썬에서 import로 모듈을 가져오면 해당 스크립트 파일이 한 번 실행되고 hello.py의 __name__ 변수에는 "hello"가 들어가고, main.py의 __name__ 변수에는 '__main__'이 들어감.

 

다시 한번 정리하자면,

__name__은 모듈의 이름이 저장되는 변수이며 import로 모듈을 가져왔을 때 모듈의 이름이 들어감.

하지만 파이썬 인터프리터로 스크립트 파일을 직접 실행했을 때는 모듈의 이름이 아니라 '__main__'이 들어감.

 

그리고 어떤 스크립트 파일이든 파이썬 인터프리터가 최초로 실행한 파일의 __name__에는 '__main__'이 들어감.

이것은 프로그램의 시작점(entry point)라는 뜻.

 

 

클래스나 변수 등을 포함한 모듈

 

모듈 만들기

%%writefile sample_module.py
PYTHON_VERSION = "Python 3.10.10"

class Calc:
    def __init__(self, x, y, w):
        self.height = x
        self.base  = y
        self.upper = w
        
    def triangle(self):
        return (self.height * self.base) / 2
    
    def rectangle(self):
        return self.height * self.base

    def trapezoid(self):
        return (self.base + self.upper)*self.height / 2
    
def summation(z):
    return sum(range(z+1))

 

불러오기

from sample_module import PYTHON_VERSION, Calc, summation

print(PYTHON_VERSION)

calc = Calc(10, 20)
print(calc.triangle())
print(calc.rectangle())
print(calc.trapezoid())

print(summation(100))

주의!!

주피터 노트북에서 동일한 모듈 import는 단 한 번만 수행된다는 것을 명심!

(여러 번 해도 항상 첫 import된 내용만 가지고 있어서 필요시 커널 재부팅)

(Select kernel 에서 No kernel로 바꾸기)

 

3. as

from sample_module import summation as s

s(100)

 

파이썬 예외처리 사용하기

예외(exception)란 코드를 실행하는 중에 발생한 오류를 의미함.

(ZeroDivisionError, AttributeError, NameError, TypeError 등등)

try, except을 이용해서 예외가 발생했을 때도 코드 실행을 중단하지 않고 계속 실행하게 해줄 수 있음.

 

4. try

5. except

def div_10_by(x):
	return 10/x
    
try:
	x = int(input())
    y = div_10_by(x)
    print(y)
    
except:
	print("예외 발생")

이렇게 하면 input을 0으로 해버리면 ZeroDivisionError가 발생해야하는데, except을 걸어주었기 때문에 예외가 발생했다고 인식하고 해당 줄에서 코드 실행을 중단하고 바로 except로 가서 코드를 실행해줌.

그러니깐 y = div_10_by(x)를 실행해줄려고 했는데 x가 0이어서 예외가 발생할 거니깐 코드 실행 중단하고 except 쪽으로 가서 코드를 실행함. 

 

특정 예외만 처리하기

a_list = [50, 40, 30, 20, 10]

try:
    index = int(input("리스트의 인덱스를 입력하세요 >>> "))
    value = int(input("해당 원소의 나눌 값을 입력하세요"))
    result = a_list[index] / value
    print("result =", result)

except ZeroDivisionError: #except ZeroDivisionError as e
    print("숫자를 0으로 나눌 순 없습니다.")

except IndexError: #except IndexError as e
    print("잘못된 인덱스입니다.")

 

6. else

7. finaly

try:
	실행할 코드
    
except:
	예외가 발생했을 때 처리하는 코드
    
else:
	예외가 발생하지 않았을 때 실행할 코드
    
finally:
	예외 발생 여부와 상관없이 항상 실행할 코드

else는 except 바로 다음에 와야 하며 except를 생략할 수는 없음.

finally는 except와 else를 생략할 수 있음.

try는 함수가 아니므로 지역변수와 무관함.

따라서 try 안에서 변수를 만들더라도 try 바깥에서 사용가능.

 

else 사용 예시

num_list = [23,145,1551,2451,5121]

try:
    index = int(input("리스트의 인덱스를 입력하시오 >>> "))
    value = int(input("해당 원소의 나눌 값을 입력하세요. >>> "))
    result = num_list[index] / value

except Exception as e:
    print("예외가 발생하였습니다.", e)

else:
    print("result =", result)

 

finally 사용 예시

num_list = [100,90,80,70,60]

try:
    index = int(input("리스트의 인덱스를 입력하세요 >>> "))
    value = int(input("해당 원소의 나눌 값을 입력하세요 >>> "))
    result = num_list[index] / value

except Exception as e:
    print("예외 발생:", e)

else:
    print("result =",result)

finally:
    print("코드의 수행이 종료되었습니다.")

 

 

8. raise

사용자가 정의한 예외 발생시키기

try:
    even_number = int(input("짝수를 입력하세요 >>> "))
    if even_number % 2 == 0: # 짝수가 아니면 예외 발생
        print(f"{even_number}는 짝수 입니다.")
    else:
        raise Exception("짝수가 아닙니다.")
        
except Exception as e:
    print("예외가 발생하였습니다.", e)

 

raise의 처리과정

def is_even_number():
	even_number = int(input("짝수를 입력하세요 >>> "))
    if even_number % 2 == 0:
    	print(f"{even_number}는 짝수입니다.")
    
    else:
    	raise Exception("짝수가 아닙니다.")
        

try:
	is_even_number()
    
except Exception as e:
	print("예외가 발생하였습니다", e)

is_even_number 함수는 안에 try except이 없는 상태에서 raise로 예외를 발생시켰다.

이렇게 되면 함수 바깥에 있는 except에서 예외가 처리된다.

 

예외가 발생하더라도 현재 코드 블록에서 처리해줄 except가 없다면

except가 나올 때까지 계속 상위 코드 블록으로 올라간다.

 

만약 함수 바깥에도 처리해 줄 except가 없다면 코드 실행은 중지되고 에러가 표시됨. 

 

예외 다시 발생시키기

def is_even_number():
    try: 
        even_number = int(input("짝수를 입력하세요 >>> "))
        if even_number % 2 == 0: # 짝수가 아니면 예외 발생
            print(f"{even_number}는 짝수 입니다.")
        else:
            raise Exception("짝수가 아닙니다.")
            
    except Exception as e:
        print("is_even_number() 함수에서 예외가 발생하였습니다.", e)
        raise # raise로 현재 예외를 다시 발생시켜 상위 코드 블럭으로 넘김
    
try:
    is_even_number()
    
except Exception as e:
    print("하위 코드 블럭에서 예외가 발생하였습니다.", e)
def is_even_number():
    try: 
        even_number = int(input("짝수를 입력하세요 >>> "))
        if even_number % 2 == 0: # 짝수가 아니면 예외 발생
            print(f"{even_number}는 짝수 입니다.")
        else:
            raise Exception("짝수가 아닙니다.")
            
    except Exception as e:
        print("예외가 발생하였습니다.", e)
        raise RuntimeError("is_even_number 함수에서 예외가 발생하였습니다.")
    
try:
    is_even_number()
    
except RuntimeError as e:
    print("하위 코드 블럭에서 예외가 발생하였습니다.", e)

 

9. assert

assert 조건식
assert 조건식, 에러메시지

assert는 지정된 조건식이 거짓일 때 AssertionError 예외를 발생시키며 

조건식이 참이면 그냥 넘어갑니다.

 

try:
	even_number = int(input("짝수 입력: "))
    assert even_number % 2 == 0 
    
except Exception as e:
	print("예외가 발생하였습니다.")

 

 

+ 참고

jupyter 창에서는

!pip install pyfiglet

 

터미널에서

pip install pyfiglet

pip show pyfiglet

 

ctrl_c 로 중단

 

jupyter 에서는 clear라는 명령 불가

 

+ Recent posts