Python Camp

Logo

Life is short. You need Python.

Module

Why Use Module

%%writefile arithmetic.py
def add(x, y):
    """
    x+y
    """
    return x + y

def sub(x, y):
    """
    x-y
    """
    return x - y

def mul(x, y):
    """
    x*y
    """
    return x*y

def div(x, y):
    """
    x/y
    """
    return x/y
import 모듈이름
import arithmetic
print(arithmetic.add(5, 2))
print(arithmetic.sub(5, 2))
print(arithmetic.mul(5, 2))
print(arithmetic.div(5, 2))
import 모듈이름 as 별칭
import arithmetic as am
print(am.add(5, 2))
print(am.sub(5, 2))
print(am.mul(5, 2))
print(am.div(5, 2))
from 모듈이름 import 모듈 함수 
from 모듈이름 import * 
from arithmetic import *
print(add(5, 2))
print(sub(5, 2))
print(mul(5, 2))
print(div(5, 2))
from 모듈이름 import 모듈함수 as 별칭
from arithmetic import add as func_1
from arithmetic import sub as func_2
from arithmetic import mul as func_3
from arithmetic import div as func_4
print(func_1(5, 2))
print(func_2(5, 2))
print(func_3(5, 2))
print(func_4(5, 2))

Package

--self_package
  -- __init__.py
  -- test_math.py
  -- module1
    -- test_math.py
  -- module2
    -- test_math.py
    

test_math.py 내용은 다음 과 같음.

#test_math.py
def add(x, y):
    """
    x+y
    """
    return x + y

def sub(x, y):
    """
    x-y
    """
    return x - y

def mul(x, y):
    """
    x*y
    """
    return x*y

def div(x, y):
    """
    x/y
    """
    return x/y
# docstring에서 file 경로 확인!
from self_package import test_math as package
print(package.add(1, 2))
print(package.sub(1, 2))
print(package.mul(1, 2))
print(package.div(1, 2))
# docstring에서 file 경로 확인!
from self_package.module1 import test_math as module1
print(module1.add(1, 2))
print(module1.sub(1, 2))
print(module1.mul(1, 2))
print(module1.div(1, 2))
# docstring에서 file 경로 확인!
from self_package.module2 import test_math as module2
print(module2.add(1, 2))
print(module2.sub(1, 2))
print(module2.mul(1, 2))
print(module2.div(1, 2))
from test_dir.sub_test1 import test as sub1
sub1.add()
from test_dir.sub_test2 import test as sub2

Built-in Functions

# abs()
print("Test abs : ", abs(-5))

# sum()
print("Test sum : ", sum([1, 2, 4, 5, 6, 7]))

# max()
print("Test max : ", max(50, 30, 10, 55, 20, 300))

# min()
print("Test min : ", min(50, 30, 10, 55, 20, 300))

# pow()
print("Test pow : ", pow(5, 4))

# round()
print("Test round : ", round(3.2245))

# sorted()
print("Test sorted : ", sorted([5,4,3,2,1]))

# len()
print("Test len : ", len("python"))

외장 함수 (표준 라이브러리)

import random
random.randint(1, 9)
8
import glob
# * 은 와일드카드 라고 하며 여러 파일을 한꺼번에 지정할 때 사용.
glob.glob('./*.py')
['./lambda_yield.py',
 './arithmetic.py',
 './assignment_solution.py',
 './my_math.py']

와일드카드

Error & Exception

Built-in exception

print("sdw"
if i:
print("Hello")
print(test)
print(2/0)
print("4"+5)
print(5+"3")

try/except/else/finally

# try/except
try:
    print("try clause")
    x = int(input("Please input a number : "))
except :
    print("except clause")
    print("Oops! That was no valid number.  Try again...")

#try/except/except
try:
    print("Try clause")
    x = int(input("Please input a number : "))
    print(y)
except ValueError:
    print("1st except clause")
    print("ValueError !")
    
except NameError:
    print("2nd except clause")
    print("NameError !")
try:
    print("Try clause")
    x = int(input("Please input a number : "))
    print(y)
except ValueError as e:
    print("1st except clause")
    print("ValueError !")
    print(e)
    
except NameError as e:
    print("2nd except clause")
    print("NameError")
    print(e)

try:
    print("\n---------------------")
    print("Try clause")
    x = int(input("Please input a number : "))
except ValueError as e:
    print("\n---------------------")
    print("except clause")
    print(e)

else:
    print("\n---------------------")
    print("nelse clause")
    print("x is ", x)
    
finally:
    print("\n---------------------")
    print("finally clause")
    print("End Exception")
try:
    raise Exception("Exception!", "What!?")
except Exception as e:
    print(e)
    print(type(e))
    print(e.args)

자신 만의 Exception & raise

class SelfError(Exception) : 
    pass
while True:
    try:
        print("\n---------------------")
        print("Try clause")
        x = int(input("Please input a number : "))
        if x<10:
            raise SelfError("args1", "args2")
        break
        
    except ValueError as e:
        print("\n---------------------")
        print("1st except clause")
        print(e)
    
    except SelfError as e:
        print("\n---------------------")
        print("2nd except clause")
        print(e)
        raise
while True:
    try:
        print("\n---------------------")
        print("Try clause")
        x = int(input("Please input a number : "))
        if x<10:
            raise SelfError()
        break
        
    except ValueError as e:
        print("\n---------------------")
        print("1st except clause")
        print(e)
    
    except SelfError as e:
        print("\n---------------------")
        print("2nd except clause")
        print(e)
        raise
try:
    print("\n---------------------")
    print("Try clause")
    x = int(input("Please input a number : "))
    if x <10:
        raise ValueError("Lower than 10!!")
except ValueError as e:
    print("\n---------------------")
    print("except clause")
    raise

else:
    print("\n---------------------")
    print("else clause")
    print("x is ", x)
    
finally:
    print("\n---------------------")
    print("finally clause")
    print("End Exception")
while True:
    try:
        print("\n---------------------")
        print("Try clause")
        x = int(input("Please input a number : "))
        if x <10:
            raise ValueError("Lower than 10!!")
        
    except ValueError as e:
        print("\n---------------------")
        print("except clause")
        print(e)
        #raise
    
    else:
        print("\n---------------------")
        print("else clause")
        print("Now is else time.")
        break
        
    finally:
        print("\n---------------------")
        print("finally clause")
        print("End Exception")

assert

test_assertion = [1, 2, 3, 4]
assert len(test_assertion) == 3, "Assertion Error!"
def confirm_int(x):
    assert type(x) == int, "x is not int !"
    return x
confirm_int(0.2)

To Home
To Lecture List