%%writefile Module.py def func1(): print("Module.py : func1()") # def func2(): print("Module.py : func2()") # def func3(): print("Module.py : func3()") #Writing Module.py
!ls #Module.py sample_data
%load Module.py
%run Module.py
import Module Module.func1() Module.func2() Module.func3() #Module.py : func1() #Module.py : func2() #Module.py : func3()
from Module import * Module.func1() Module.func2() Module.func3() #Module.py : func1() #Module.py : func2() #Module.py : func3()
%%writefile Calculator.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 # def mod(a, b): return a%b #Writing Calculator.py
from Calculator import * print(add(3,5)) print(sub(3,5)) print(mul(3,5)) print(div(3,5)) print(mod(3,5)) #8 #8 #15 #0.6 #3
import sys print(sys.builtin_module_names) #('_abc', '_ast', '_bisect', '_blake2', '_codecs', '_collections', '_csv', '_datetime', '_elementtree', '_functools', '_heapq', '_imp', '_io', '_locale', '_md5', '_operator', '_pickle', '_posixsubprocess', '_random', '_sha1', '_sha256', '_sha3', '_sha512', '_signal', '_socket', '_sre', '_stat', '_statistics', '_string', '_struct', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', 'array', 'atexit', 'binascii', 'builtins', 'cmath', 'errno', 'faulthandler', 'fcntl', 'gc', 'grp', 'itertools', 'marshal', 'math', 'posix', 'pwd', 'pyexpat', 'select', 'spwd', 'sys', 'syslog', 'time', 'unicodedata', 'xxsubtype', 'zlib')
print(dir(__builtins__)) #['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__IPYTHON__', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'display', 'divmod', 'enumerate', 'eval', 'exec', 'execfile', 'filter', 'float', 'format', 'frozenset', 'get_ipython', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'repr', 'reversed', 'round', 'runfile', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
import time
필요import time print(dir(time)) #['CLOCK_BOOTTIME', 'CLOCK_MONOTONIC', 'CLOCK_MONOTONIC_RAW', 'CLOCK_PROCESS_CPUTIME_ID', 'CLOCK_REALTIME', 'CLOCK_TAI', 'CLOCK_THREAD_CPUTIME_ID', '_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'clock_getres', 'clock_gettime', 'clock_gettime_ns', 'clock_settime', 'clock_settime_ns', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'monotonic_ns', 'perf_counter', 'perf_counter_ns', 'process_time', 'process_time_ns', 'pthread_getcpuclockid', 'sleep', 'strftime', 'strptime', 'struct_time', 'thread_time', 'thread_time_ns', 'time', 'time_ns', 'timezone', 'tzname', 'tzset']
time
예제import timeimport time print(dir(time)) print(time) print(time.time()) print(time.time()) print(time.time()) # now = time.gmtime(time.time()) print(now) # year = str(now.tm_year) month = str(now.tm_mon) day = str(now.tm_mday) print(year, "년", month + "월", day + "일") # hour = str(now.tm_hour) minute = str(now.tm_min) sec = str(now.tm_sec) print(hour + "시", minute + "분", sec + "초") #<module 'time' (built-in)> #1704500880.235648 #1704500880.2361746 #1704500880.2367284 #time.struct_time(tm_year=2024, tm_mon=1, tm_mday=6, tm_hour=0, #tm_min=28, tm_sec=0, tm_wday=5, tm_yday=6, tm_isdst=0) #2024 년 1월 6일 #0시 28분 0초
datetime
의 date
클래스 예제from datetime import date print(date) print(date(2000,1,1)) print(date(year=2000, month=1, day=1)) print(date.today()) # today = date.today() year = str(today.year) month = str(today.month) day = str(today.day) weekday = "월화수목금토일"[(today.weekday())] print(year + "년", month + "월", day + "일", weekday + "요") #<class 'datetime.date'> #2000-01-01 #2000-01-01 #2024-01-06 #2024년 1월 6일 토요
datetime
의 time
클래스 예제from datetime import time print(time) print(time(12,0)) print(time(14,30)) print(time(16,30,45)) print(time(18,00,15,100000)) # now = time(20,40,15,20000) hour = str(now.hour) minute = str(now.minute) sec = str(now.second) msec = str(now.microsecond) print(hour + "시", minute + "분", sec+"초", msec + "마이크로초") #<class 'datetime.time'> #12:00:00 #14:30:00 #16:30:45 #18:00:15.100000 #20시 40분 15초 20000마이크로초
from datetime import datetime print(datetime) print(datetime(2020,1,1)) print(datetime(2020,1,1,1,15,45)) print(datetime.now()) now = datetime.now() print(now.strftime("%Y년 %m월 %d일 %H시, %M분 %S초")) print(now.strftime("%y/%m/%d %p %l:%M:%S:%f")) #<class 'datetime.datetime'> #2020-01-01 00:00:00 #2020-01-01 01:15:45 #2024-01-06 01:31:36.680410 #2024년 01월 06일 01시, 31분 36초 #24/01/06 AM 1:31:36:680532
from datetime import date birthday = date(2000,1,1) today = date.today() day = today - birthday print(day.days) #8771
파이썬에서 수학에 필요한 math 모듈
제공
import math print(dir(math)) #['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
itertools 모듈
에서 곱집합, 순열, 조합 등을 구하는 함수 제공import math print(math.factorial(3)) print(math.gcd(12,24)) print(math.floor(math.pi)) print(math.ceil(math.pi)) print(math.pow(2,10)) print(math.sqrt(10)) print(math.log(10,2)) print(math.degrees(math.pi)) print(math.radians(180)) print(math.sin(math.radians(90))) print(math.cos(math.radians(180))) #6 #12 #3 #4 #1024.0 #3.1622776601683795 #3.3219280948873626 #180.0 #3.141592653589793 #1.0 #-1.0
import itertools list_1 = ['a', 'b', 'c'] print(list_1) list_2 = [1,2] print(list_2) list_cp = list(itertools.product(list_1, list_2)) print(list_cp) list_p = list(itertools.permutations(list_1, 2)) print(list_p) list_c = list(itertools.combinations(list_1, 2)) print(list_c) list_cr = list(itertools.combinations_with_replacement(list_1,2)) print(list_cr) #['a', 'b', 'c'] #[1, 2] #[('a', 1), ('a', 2), ('b', 1), ('b', 2), ('c', 1), ('c', 2)] #[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')] #[('a', 'b'), ('a', 'c'), ('b', 'c')] #[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')]
statistics 모듈
에서는 산술평균, 표준편차 등 통계에 필요한 계산 관련 함수들을 제공import statistics values = [56,44,67,47,82,67,92,89,81,82] print(statistics.median(values)) print(statistics.mean(values)) print(statistics.harmonic_mean(values)) print(statistics.stdev(values)) print(statistics.variance(values)) #74.0 #70.7 #66.42170307761845 #17.217884758458442 #296.4555555555556
import random
필요import random print(random.random()) print(random.randint(1,10)) print(random.randrange(0,10,2)) #0.4163501217036304 #4 #2
li = [10,20,30,40,50] print(li) print(random.choice(li)) print(random.sample(li,2)) random.shuffle(li) print(li) #[10, 20, 30, 40, 50] #20 #[40, 10] #[50, 30, 40, 10, 20]
코드를 입력하세요
import random as rd # print(rd.random()) print(rd.randrange(0,10,2)) #0.6794502806352734 #2
from random import random, randrange # print(random()) print(randrange(0,10,2)) #0.11061294619766726 #4
from random import * # print(random()) print(randrange(0,10,2)) #0.8081972962122512 #4
!mkdir package !mkdir package/sub_package_1 !mkdir package/sub_package_2 !mkdir package/sub_package_3
!ls package
%%writefile package/sub_package_1/sub1_module_1.py def print_module(): print("sub_package_1/sub1_module_2")
%%writefile package/sub_package_1/sub1_module_1.py def print_module(): print("sub_package_2/sub2_module_1")
%%writefile package/sub_package_1/sub1_module_1.py def print_module(): print("sub_package_3/sub2_module_2")
%%writefile package/sub_package_1/sub1_module_1.py def print_module(): print("sub_package_3/sub1_module_1")
%%writefile package/sub_package_1/sub1_module_1.py def print_module(): print("sub_package_3/sub1_module_2")
%%writefile package/sub_package_1/sub1_module_1.py def print_module(): print("sub_package_1/sub1_module_1")
from package.sub_package_1 import sub1_module_1, sub1_module_2 sub1_module_1.print_module() sub1_module_2.print_module()
from package.sub_package_2 import sub2_module_1, sub2_module_2 sub2_module_1.print_module() sub2_module_2.print_module()
from package.sub_package_3 import sub3_module_1, sub3_module_2 sub3_module_1.print_module() sub3_module_2.print_module()
from package import * sub1_module_1.print_module() sub1_module_2.print_module() sub2_module_1.print_module() sub2_module_2.print_module() sub3_module_1.print_module() sub3_module_2.print_module()
__init__.py
%%writefile package/__init__.py __all__ = ['sub_package_1', 'sub_package_2', 'sub_package_3']
%%writefile package/sub_package1/__init__.py __all__ = ['sub1_module_1', 'sub1_module_2']
%%writefile package/sub_package1/__init__.py __all__ = ['sub1_module_1', 'sub1_module_2']
%%writefile package/sub_package3/__init__.py __all__ = ['sub1_module_1', 'sub1_module_2']
!ls package
!ls package/sub_package_1
__main__.py
__main__.py
실행%%write package/__main__.py from sub_package_1 import * from sub_package_2 import * from sub_package_3 import * # if __name__ == '__main__': sub1_module_1.print_module() sub1_module_2.print_module() sub2_module_1.print_module() sub2_module_2.print_module() sub3_module_1.print_module() sub3_module_2.print_module()
! python package