# 계산기의 "더하기" 기능을 구현
result = 0
def adder(num):
global result # 결과값을 유지하기 위해 전역 변수 사용
result += num
return result
print(adder(3))
print(adder(5))
3 8
# 한 프로그램에서 2개의 계산기가 필요한 경우 함수를 따로 만들어야 한다.
result1 = 0
result2 = 0
def adder1(num):
global result1
result1 += num
return result1
def adder2(num):
global result2
result2 += num
return result2
print(adder1(3))
print(adder1(4))
print(adder2(3))
print(adder2(7))
3 7 3 10
# 같은 함수를 반복해서 만드는 대신 클래스를 이용해서 구현
class Calculator:
def __init__(self):
self.result = 0
def adder(self, num):
self.result += num
return self.result
cal1 = Calculator()
cal2 = Calculator()
print(cal1.adder(3))
print(cal1.adder(4))
print(cal2.adder(3))
print(cal2.adder(7))
3 7 3 10
def sub(self, num):
self.result -= num
return self.result
# 파이썬 클래스의 가장 간단한 예
class Programmer:
pass
# Programmer 클래스의 객체를 만드는 방법
kim = Programmer()
park = Programmer()
클래스에 의해서 만들어진 객체를 인스턴스라고도 한다. 객체와 인스턴스의 차이는 무엇일까? kim = Programmer() 에서 kim 은 객체이다. 그리고 kim 이라는 객체는 Programmer 의 인스턴스이다. 즉, 인스턴스라는 말은 특정 객체(kim)가 어떤 클래스(Programmer)의 객체인지를 관계 위주로 설명할 때 사용한다. 즉, "kim은 인스턴스" 보다는 "kim은 객체다"라는 표현이 어울리며, "kim은 Programmer의 객체" 보다는 "kim은 Programmer의 인스턴스"라는 표현이 잘 어울린다.
class Service:
secret = "영구는 외계인이다."
pey = Service()
pey.secret
'영구는 외계인이다.'
juhoi = Service()
juhoi.secret
'영구는 외계인이다.'
juhoi.secret = "나는 외계인이다."
pey.secret
'영구는 외계인이다.'
# 클래스 변수 직접 접근하기
Service.secret
'영구는 외계인이다.'
Service.secret = "영구는 도깨비이다."
Service.secret
'영구는 도깨비이다.'
pey.secret
'영구는 도깨비이다.'
juhoi.secret
'나는 외계인이다.'
duckbabys = Service()
duckbabys.secret
'영구는 도깨비이다.'
Service.secret = "도깨비 OST"
print(pey.secret)
print(juhoi.secret)
print(duckbabys.secret)
도깨비 OST 나는 외계인이다. 도깨비 OST
class Service:
secret = "영구는 외계인이다."
def sum(self, a, b):
result = a + b
print("%s + %s = %s 입니다" % (a, b, result))
pey = Service()
pey.sum(1, 1)
1 + 1 = 2 입니다
pey = Service()
Service.sum(pey, 1, 1)
class Service:
secret = "영구는 외계인이다"
def setname(self, name):
self.name = name
def sum(self, a, b):
result = a + b
print("%s 님 %s + %s = %s 입니다." % (self.name, a, b, result))
pey = Service()
pey.setname("홍길동")
pey.sum(1, 1)
홍길동 님 1 + 1 = 2 입니다.
babo = Service()
babo.sum(1,1)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-3-31e65386a5d0> in <module>() 1 babo = Service() ----> 2 babo.sum(1,1) <ipython-input-2-3c68828fdad9> in sum(self, a, b) 8 result = a + b 9 ---> 10 print("%s 님 %s + %s = %s 입니다." % (self.name, a, b, result)) 11 12 AttributeError: 'Service' object has no attribute 'name'
class Service:
secret = "영구는 외계인이다"
def __init__(self, name): # 객체를 만들 때 항상 실행된다.
self.name = name
def sum(self, a, b):
result = a + b
print("%s 님 %s + %s = %s 입니다." % (self.name, a, b, result))
pey = Service("홍길동")
pey.sum(1, 1)
홍길동 님 1 + 1 = 2 입니다.
class FourCal:
def setdata(self, first, second):
self.first = first
self.second = second
def sum(self):
result = self.first + self.second
return result
def sub(self):
result = self.first - self.second
return result
def mul(self):
result = self.first * self.second
return result
def div(self):
result = self.first / self.second
return result
a = FourCal()
b = FourCal()
a.setdata(4, 2)
b.setdata(3, 7)
a.sum()
6
a.sub()
2
a.mul()
8
a.div()
2.0
b.sum()
10
b.sub()
-4
b.mul()
21
b.div()
0.42857142857142855
class HousePark:
lastname = "박"
def __init__(self, name):
self.fullname = self.lastname + name
def travel(self, where):
print("%s, %s 여행을 가다." % (self.fullname, where))
pey = HousePark()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-15-22c18c13dd20> in <module>() ----> 1 pey = HousePark() TypeError: __init__() missing 1 required positional argument: 'name'
pey = HousePark("응용")
pey.travel("태국")
박응용, 태국 여행을 가다.
class 상속받을 클래스명(상속할 클래스명)
class HouseKim(HousePark):
lastname = "김"
juliet = HouseKim("줄리엣")
juliet.travel("독도")
김줄리엣, 독도 여행을 가다.
class HouseKim(HousePark):
lastname = "김"
def travel(self, where):
print("%s 은 %s 로 여행합니다." % (self.fullname, where))
juliet = HouseKim("줄리엣")
juliet.travel("독도")
김줄리엣 은 독도 로 여행합니다.
class HousePark:
lastname = "박"
def __init__(self, name):
self.fullname = self.lastname + name
def travel(self, where):
print("%s, %s여행을 가다." % (self.fullname, where))
def __add__(self, other):
print("%s, %s 결혼했네" % (self.fullname, other.fullname))
class HouseKim(HousePark):
lastname = "김"
def travel(self, where):
print("%s은 %s로 여행합니다." % (self.fullname, where))
pey = HousePark("응용")
juliet = HouseKim("줄리엣")
pey + juliet
박응용, 김줄리엣 결혼했네
%%writefile mod1.py
def sum(a, b):
return a + b
Writing mod1.py
!ls
01장 파이썬이란 무엇인가?.ipynb 02장 파이썬 프로그래밍의 기초, 자료형.ipynb 03장 프로그램의 구조를 쌓는다! 제어문.ipynb 04-sys1.py 04-sys2.py 04-새파일.txt 04장 프로그램의 입력과 출력은 어떻게 해야 할까?.ipynb 05장 파이썬 날개달기.ipynb mod1.py
import mod1
print(mod1.sum(3, 4))
7
%%writefile mod1.py
def sum(a, b):
return a + b
def safe_sum(a, b):
if type(a) != type(b):
print("더할수 있는 것이 아닙니다.")
return
else:
result = sum(a, b)
return result
Overwriting mod1.py
!ls
01장 파이썬이란 무엇인가?.ipynb 02장 파이썬 프로그래밍의 기초, 자료형.ipynb 03장 프로그램의 구조를 쌓는다! 제어문.ipynb 04-sys1.py 04-sys2.py 04-새파일.txt 04장 프로그램의 입력과 출력은 어떻게 해야 할까?.ipynb 05장 파이썬 날개달기.ipynb __pycache__ mod1.py
import mod1
print(mod1.safe_sum(3, 4))
print(mod1.safe_sum(1, 'a'))
7 더할수 있는 것이 아닙니다. None
from 모듈이름 import 모듈함수
from mod1 import sum
sum(3, 4)
7
from mod1 import sum, safe_sum
from mod1 import *
%%writefile mod1.py
def sum(a, b):
return a+b
def safe_sum(a, b):
if type(a) != type(b):
print("더할수 있는 것이 아닙니다.")
return
else:
result = sum(a, b)
return result
print(safe_sum('a', 1))
print(safe_sum(1, 4))
print(sum(10, 10.4))
Overwriting mod1.py
%run mod1.py
더할수 있는 것이 아닙니다. None 5 20.4
import mod1
if __name__ == "__main__
print(safe_sum('a', 1))
print(safe_sum(1, 4))
print(sum(10, 10.4))
import sys
sys.path
['', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages', '/usr/local/lib/python3.4/dist-packages/IPython/extensions', '/root/.ipython']
가상의 game 패키지 예
game/
__init__.py
sound/
__init__.py
echo.py
wav.py
graphic/
__init__.py
screen.py
render.py
play/
__init__.py
run.py
test.py
!mkdir game game/sound game/graphic
!ls
01장 파이썬이란 무엇인가?.ipynb 02장 파이썬 프로그래밍의 기초, 자료형.ipynb 03장 프로그램의 구조를 쌓는다! 제어문.ipynb 04-sys1.py 04-sys2.py 04-새파일.txt 04장 프로그램의 입력과 출력은 어떻게 해야 할까?.ipynb 05장 파이썬 날개달기.ipynb __pycache__ game mod1.py
!touch game/__init__.py game/sound/__init__.py gamd/graphic/__init__.py
touch: `gamd/graphic/__init__.py'를 touch할 수 없음: 그런 파일이나 디렉터리가 없습니다
!touch game/graphic/__init__.py
%%writefile game/sound/echo.py
def echo_test():
print("echo")
Writing game/sound/echo.py
%%writefile game/graphic/render.py
def render_test():
print("render")
Writing game/graphic/render.py
import game.sound.echo
game.sound.echo.echo_test()
echo
from game.sound import echo
echo.echo_test()
echo
from game.sound.echo import echo_test
echo_test()
echo
from game.sound import *
echo.echo_test()
echo
!echo "__all__ = ['echo']" >> game/sound/echo.py
!more game/sound/echo.py
def echo_test(): print("echo")__all__ = ['echo']
!more game/sound/echo.py
def echo_test(): print("echo")
!more game/sound/__init__.py
__all__ = ['echo']
# 디렉터리 안에 없는 파일을 열려고 시도했을때 - FileNotFoundError
f = open("없는파일", 'r')
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) <ipython-input-1-017cc5335a6d> in <module>() 1 # 디렉터리 안에 없는 파일을 열려고 시도했을때 - FileNotFoundError 2 ----> 3 f = open("없는파일", 'r') FileNotFoundError: [Errno 2] No such file or directory: '없는파일'
# 0으로 다른 숫자를 나누는 경우 - ZeroDivisionError
4 / 0
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-2-6a687db7d11d> in <module>() 1 # 0으로 다른 숫자를 나누는 경우 - ZeroDivisionError 2 ----> 3 4 / 0 ZeroDivisionError: division by zero
# 리스트에서 얻을 없는 index 값 - IndexError
a = [1, 2, 3]
a[4]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-3-4862fae32f59> in <module>() 3 a = [1, 2, 3] 4 ----> 5 a[4] IndexError: list index out of range
try:
...
except [발생 오류[as 오류 메시지 변수]]:
...
try:
...
except:
...
try:
...
except 발생 오류:
...
try
...
except 발생 오류 as 오류 메시지 변수:
...
try:
4 / 0
except ZeroDivisionError as e:
print(e)
division by zero
try:
f = open("foo.txt", 'r')
except FileNotFoundError as e:
print(str(e))
else:
data = f.read()
f.close()
[Errno 2] No such file or directory: 'foo.txt'
f = open("foo.txt", 'w')
try:
# 무언가를 수행한다.
pass
finally:
f.close()
try:
...
except 발생 오류1:
...
except 발행 오류2:
...
try:
a = [1, 2]
print(a[3])
4/0
except ZeroDivisionError:
print("0으로 나눌 수 없습니다.")
except IndexError:
print("인덱싱 할 수 없습니다.")
인덱싱 할 수 없습니다.
# 다음과 같이 2개 이상의 오류를 동시에 처리하기 위해서는 함께 묶어주어 처리하면 된다.
try:
a = [1, 2]
print(a[3])
4/0
except (ZeroDivisionError, IndexError) as e:
print(e)
list index out of range
try:
f = open("없는 파일", 'r')
except FileNotFoundError:
pass
class Bird:
def fly(self):
raise NotImplementedError
NotImplementedError 는 파이썬 내장 오류로, 꼭 작성해야 하는 부분이 구현되지 않았을 경우 일부러 오류를 발생시키고자 사용한다.
class Eagle(Bird):
pass
eagle = Eagle()
eagle.fly()
class MyError(Exception):
pass
def say_nick(nick):
if nick == '바보':
raise MyError()
print(nick)
say_nick('천사')
say_nick('바보')
천사
--------------------------------------------------------------------------- MyError Traceback (most recent call last) <ipython-input-4-47d90292dcbe> in <module>() 1 say_nick('천사') ----> 2 say_nick('바보') <ipython-input-3-1b9fee73a580> in say_nick(nick) 1 def say_nick(nick): 2 if nick == '바보': ----> 3 raise MyError() 4 print(nick) MyError:
try:
say_nick('천사')
say_nick('바보')
except MyError:
print("허용되지 않는 별명입니다.")
천사 허용되지 않는 별명입니다.
try:
say_nick('천사')
say_nick('바보')
except MyError as e:
print(e)
천사
class MyError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
def say_nick(nick):
if nick == '바보':
raise MyError("허용되지 않는 별명입니다.")
print(nick)
try:
say_nick("천사")
say_nick("바보")
except MyError as e:
print(e)
천사 허용되지 않는 별명입니다.
# abs: 어떤 숫자를 입력 받았을 때, 그 숫자의 절대값을 돌려주는 함수
abs(3)
3
abs(-3)
3
abs(-1.2)
1.2
# all: 반복 가능한(iterable), 자료형(리스트, 튜플, 문자열, 딕셔너리, 집합 등) x가 모두 참이면 True, 아니면 False 를 리턴
all([1, 2, 3])
True
all([1, 2, 3, 0])
False
# any: x 중 하나라도 참이면 True, x 가 모두 거짓일 경우에민 False 를 리턴, all(x) 의 반대 경우
any([1, 2, 3, 0])
True
any([0, ''])
False
# chr: 아스키(ascii) 코드값을 입력받아 그 코드에 해당하는 문자를 출력
chr(97)
'a'
chr(48)
'0'
# dir: 객체가 자체적으로 가지고 있는 변수나 함수(메서드)를 출력
dir([1, 2, 3])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
dir({'1': 'a'})
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
# divmod(a, b): a를 b로 나눈 몫과 나머지를 튜플 형태로 리턴
divmod(7, 3)
(2, 1)
divmod(1.3, 0.2)
(6.0, 0.09999999999999998)
# enumerate: 순서가 있는 자료형(리스트, 튜플, 문자형)을 입력받아 인덱스 값을 포함하는 enumerate 객체를 리턴
enumerate(['body', 'far', 'bar'])
<enumerate object at 0x7fa880980a68>
for i, name in enumerate(['body', 'far', 'bar']):
print(i, name)
0 body 1 far 2 bar
# eval: 실행 가능한 문자열을 입력받아 문자열을 실행한 결과값을 리턴
eval('1+2')
3
eval("'hi' + 'a'")
'hia'
eval("divmod(4, 3)")
(1, 1)
# filter: 첫번째 인자로 함수 이름을, 두번째 인자로 앞 함수에 차례로 넘길 반복 가능한 자료형을 넣는다.
# 두번째 인자가 차례로 첫번째 인자인 함수에 입력되어 참인 경우에만 다시 묶어서 반환한다.
# 양수값만 리턴
def positive(l):
result = []
for i in l:
if i > 0:
result.append(i)
return result
print(positive([1,-3,2,0,-5,6]))
[1, 2, 6]
# fileter 함수로 구현
def positive(x):
return x > 0
print(list(filter(positive, [1,-3,2,0,-5,6])))
[1, 2, 6]
print(list(filter(lambda x: x>0, [1, -3, 2, 0, -5, 6])))
[1, 2, 6]
# hex: 정수를 입력받아 16진수로 변화하여 리턴
hex(234)
'0xea'
hex(3)
'0x3'
# id(object): 객체를 입력받아 객체의 고유 주소값(레퍼런스)을 리턴
a = 3
id(3)
10055616
id(a)
10055616
b = a
id(b)
10055616
id(4)
10055648
# input: 사용자 입력을 받는 함수
a = input()
hi
print(a)
hi
b = input("Enter: ")
Enter: hi
b
'hi'
# int: 숫자 형태의 문자열이나 소수점이 있는 숫자등을 입력받아 정수를 리턴
int('3')
3
int(3.4)
3
# 2진수로 표현된 '11'을 10진수로 반환
int('11', 2)
3
# 16진수로 표현된 '1A'를 10진수로 반환
int('1A', 16)
26
# isinstance(object, class): 첫 번째 인수로 인스턴스, 두 번째 인수로 클래스 이름을 받는다.
# 입력받은 인스턴스가 그 클래스의 인스턴스인지를 판단하여 참이면 True, 거짓이면 False를 리턴한다.
class Person: pass
a = Person()
isinstance(a, Person)
True
b = 3
isinstance(b, Person)
False
lambda 인수1, 인수2, ... : 인수를 이용한 표현식
sum = lambda a, b: a+b
sum(3, 4)
7
myList = [lambda a,b: a+b, lambda a,b: a*b]
myList
[<function __main__.<lambda>>, <function __main__.<lambda>>]
myList[0](3, 4)
7
myList[1](5, 3)
15
# len: 입력값의 길이(요소의 전체 개수)를 리턴
len('Python')
6
len([1, 2, 3])
3
len([1, 'a'])
2
# list: 반복 가능한 자료형dmf 입력받아 리스트로 만들어 리턴
list('Python')
['P', 'y', 't', 'h', 'o', 'n']
list((1,2,3))
[1, 2, 3]
# map(f, iterable): 함수(f)와 반복 가능한(iterable) 자료형을 입력으로 받는다.
# map은 입력받은 자료형의 각 요소가 함수 f에 의해 수행된 결과를 묶어서 리턴하는 함수
def two_times(numberList):
result = [ ]
for number in numberList:
result.append(number*2)
return result
result = two_times([1, 2, 3, 4])
print(result)
[2, 4, 6, 8]
# map 으로 구현
def two_times(x): return x*2
list(map(two_times, [1, 2, 3, 4]))
[2, 4, 6, 8]
# lambda 함수까지 사용하면
list(map(lambda x: x*2, [1,2,3,4]))
[2, 4, 6, 8]
# max(iterable): 인수로 반복 가능한 자료형을 입력받아 그 최대값을 리턴
max([1,2,3])
3
max('Python')
'y'
# min(iterable): max 함수와 반대로, 인수로 반복 가능한 자료형을 입력받아 그 최소값을 리턴
min([1,2,3])
1
min('Python')
'P'
min('python')
'h'
# oct(x): 정수 형태의 숫자를 8진수 문자열로 바꾸어 리턴
oct(34)
'0o42'
oct(12345)
'0o30071'
# open(filename, [mode]): "파일 이름"과 "읽기 방법"을 입력받아 파일 객체를 리턴하는 함수
# 읽기 방법(mode)이 생략되면 기본값인 읽기 전용 모드(r)로 파일 객체를 만들어 리턴
# [04-3 파일 읽고 쓰기] 참조
# ord(c): 문자의 아스키 코드값을 리턴
# ord 함수는 chr 함수와 반대이다.
ord('a')
97
ord('0')
48
# pow(x, y): x의 y 제곱한 결과값을 리턴
pow(2, 4)
16
pow(3, 3)
27
# range([start,] stop [,step]): for문과 함께 자주 사용되는 함수
# 입력받은 숫자에 해당되는 범위의 값을 반복 가능한 객체로 만들어 리턴
# 인수가 하나일 경우
list(range(5))
[0, 1, 2, 3, 4]
# 인수가 둘일 경우
list(range(5, 10))
[5, 6, 7, 8, 9]
# 인수가 셋인 경우
list(range(1, 10, 2))
[1, 3, 5, 7, 9]
list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
# sorted(iterable): 입력값을 정렬한 후 그 결과를 리스트로 리턴
sorted([3, 1, 2])
[1, 2, 3]
sorted(['a', 'c', 'b'])
['a', 'b', 'c']
sorted("zero")
['e', 'o', 'r', 'z']
sorted((3, 2, 1))
[1, 2, 3]
a = [3, 1, 2]
result = a.sort()
print(result)
None
a
[1, 2, 3]
# str(object): 문자열 형태로 객체를 변환하여 리턴
str(3)
'3'
str('hi')
'hi'
'hi'
'hi'
str('hi'.upper())
'HI'
'hi'.upper()
'HI'
# tuple(iterable): 반복 가능한 자료형을 입력받아 튜플 형태로 바꾸어 리턴
tuple('abc')
('a', 'b', 'c')
tuple([1,2,3])
(1, 2, 3)
tuple((1,2,3))
(1, 2, 3)
# type(object): 입력값의 자료형이 무엇인지 알려주는 함수
type("abc")
str
type([ ])
list
type(open("test", 'w'))
_io.TextIOWrapper
# zip(iterable*): 동일한 개수로 이루어진 자료형을 묶어 주는 역할을 하는 함수
zip([1, 2, 3], [4, 5, 6])
<zip at 0x7fa8800b9b88>
list(zip([1, 2, 3], [4, 5, 6]))
[(1, 4), (2, 5), (3, 6)]
list(zip([1, 2, 3], [4, 5, 6], [7, 8, 9]))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
list(zip("abc", "def"))
[('a', 'd'), ('b', 'e'), ('c', 'f')]
%%writefile argv_test.py
import sys
print(sys.argv)
Writing argv_test.py
!ls
01장 파이썬이란 무엇인가?.ipynb 02장 파이썬 프로그래밍의 기초, 자료형.ipynb 03장 프로그램의 구조를 쌓는다! 제어문.ipynb 04-sys1.py 04-sys2.py 04-새파일.txt 04장 프로그램의 입력과 출력은 어떻게 해야 할까?.ipynb 05장 파이썬 날개달기.ipynb __pycache__ argv_test.py foo.txt game mod1.py test
%run argv_test.py you need Python
['argv_test.py', 'you', 'need', 'Python']
import sys
print(sys.path)
['', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages', '/usr/local/lib/python3.4/dist-packages/IPython/extensions', '/root/.ipython']
import pickle
f = open("test.txt", "wb")
data = {"1": "python", "2": "you need"}
pickle.dump(data, f)
f.close()
!ls
01장 파이썬이란 무엇인가?.ipynb __pycache__ 02장 파이썬 프로그래밍의 기초, 자료형.ipynb argv_test.py 03장 프로그램의 구조를 쌓는다! 제어문.ipynb foo.txt 04-sys1.py game 04-sys2.py mod1.py 04-새파일.txt test 04장 프로그램의 입력과 출력은 어떻게 해야 할까?.ipynb test.txt 05장 파이썬 날개달기.ipynb
!more test.txt
�}q
import pickle
f = open("test.txt", "rb")
data = pickle.load(f)
print(data)
{'2': 'you need', '1': 'python'}
import os
os.environ
environ({'USER': 'root', 'PAGER': 'cat', 'PS1': '<bg$>', 'LD_PRELOAD': '/usr/lib/coreutils/libstdbuf.so', 'LOGNAME': 'root', 'SHLVL': '2', 'LESSOPEN': '| /usr/bin/lesspipe %s', 'LESSCLOSE': '/usr/bin/lesspipe %s %s', 'MPLBACKEND': 'module://ipykernel.pylab.backend_inline', 'JPY_PARENT_PID': '441', 'SSH_TTY': '/dev/pts/2', 'SSH_CLIENT': '172.17.0.1 38904 22', 'LANG': 'ko_KR.UTF-8', 'LS_COLORS': 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.axa=00;36:*.oga=00;36:*.spx=00;36:*.xspf=00;36:', 'SSH_CONNECTION': '172.17.0.1 38904 172.17.0.13 22', 'HOME': '/root', 'OLDPWD': '/root', 'TERM': 'xterm-color', 'GIT_PAGER': 'cat', 'PATH': '/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games', '_': '/usr/bin/stdbuf', 'SHELL': '/bin/bash', 'CLICOLOR': '1', 'PWD': '/workspace/myNotebook', 'MAIL': '/var/mail/root', '_STDBUF_O': '0'})
os.environ["path"]
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-2-44c42c2e5d86> in <module>() ----> 1 os.environ["path"] /usr/lib/python3.4/os.py in __getitem__(self, key) 631 except KeyError: 632 # raise KeyError with the original key value --> 633 raise KeyError(key) from None 634 return self.decodevalue(value) 635 KeyError: 'path'
os.environ['PATH']
'/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games'
os.getcwd()
'/workspace/myNotebook/점프 투 파이썬'
os.system('dir')
0
import os
print(os.system('ls'))
0
f = os.popen("ls")
print(f.read())
01장 파이썬이란 무엇인가?.ipynb 02장 파이썬 프로그래밍의 기초, 자료형.ipynb 03장 프로그램의 구조를 쌓는다! 제어문.ipynb 04-sys1.py 04-sys2.py 04-새파일.txt 04장 프로그램의 입력과 출력은 어떻게 해야 할까?.ipynb 05장 파이썬 날개달기.ipynb __pycache__ argv_test.py foo.txt game mod1.py test test.txt
함수 | 설명 |
---|---|
os.mkdir() | 디렉터리 생성 |
os.rmdir() | 디렉터리 삭제, 단 디렉터리가 비어있어야 함 |
os.unlink() | 파일을 지운다. |
os.rename(src, dst) | 파일명 변경 |
!ls
01장 파이썬이란 무엇인가?.ipynb __pycache__ 02장 파이썬 프로그래밍의 기초, 자료형.ipynb argv_test.py 03장 프로그램의 구조를 쌓는다! 제어문.ipynb foo.txt 04-sys1.py game 04-sys2.py mod1.py 04-새파일.txt test 04장 프로그램의 입력과 출력은 어떻게 해야 할까?.ipynb test.txt 05장 파이썬 날개달기.ipynb
!more foo.txt
!more test
!more argv_test.py
import sys print(sys.argv)
import shutil
shutil.copy("argv_test.py", "argv_test2.py")
'argv_test2.py'
!ls
01장 파이썬이란 무엇인가?.ipynb __pycache__ 02장 파이썬 프로그래밍의 기초, 자료형.ipynb argv_test.py 03장 프로그램의 구조를 쌓는다! 제어문.ipynb argv_test2.py 04-sys1.py foo.txt 04-sys2.py game 04-새파일.txt mod1.py 04장 프로그램의 입력과 출력은 어떻게 해야 할까?.ipynb test 05장 파이썬 날개달기.ipynb test.txt
!more argv_test2.py
import sys print(sys.argv)
import glob
glob.glob("./04*")
['./04-sys2.py', './04장 프로그램의 입력과 출력은 어떻게 해야 할까?.ipynb', './04-sys1.py', './04-새파일.txt']
import tempfile
filename = tempfile.mktemp()
filename
'/tmp/tmp2wexrlak'
f = tempfile.TemporaryFile()
print(f)
f.close()
<_io.BufferedRandom name=58>
# time.time : 현재 시간을 실수 형태로 리턴, 1970년 1월 1일 기준으로 지난 시간을 초 단위로 리턴
import time
time.time()
1506492100.01737
# time.localtime : time.time()에 의해서 반환된 실수값을 이용해서 연도, 월, 일, 시, 분, 초 의 형태로 바꾸어 주는 함수
time.localtime(time.time)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-16-fb4b177d66f3> in <module>() 1 # time.localtime : time.time()에 의해서 반환된 실수값을 이용해서 연도, 월, 일, 시, 분, 초 의 형태로 바꾸어 주는 함수 ----> 2 time.localtime(time.time) TypeError: an integer is required (got type builtin_function_or_method)
time.localtime(time.time())
time.struct_time(tm_year=2017, tm_mon=9, tm_mday=27, tm_hour=6, tm_min=2, tm_sec=55, tm_wday=2, tm_yday=270, tm_isdst=0)
time.localtime(time.time()).tm_year
2017
# time.asctime : time.localtime에 의해서 반환된 튜플 형태의 값을 알아보기 쉬운 형태로 리턴
time.asctime(time.localtime(time.time()))
'Wed Sep 27 06:05:05 2017'
# time.ctime : 위와 같은 결과이나 항상 현재 시간만을 리턴
time.ctime()
'Wed Sep 27 06:05:52 2017'
time.strftime('출력할 형식 포맷 코드', time.localtime(time.time()))
포맷코드 | 설명 | 예 |
---|---|---|
%a | 요일 줄임말 | Mon |
%A | 요일 | Monday |
%b | 달 줄임말 | Jan |
%B | 달 | January |
%c | 날짜와 시간을 출력함 | 06/01/01 17:22:21 |
%d | 날(day) | [00, 31] |
%H | 시간 - 24시간 출력 형태 | [00, 23] |
%I | 시간 - 12시간 출력 형태 | [01, 12] |
%j | 1년 중 누적 날짜 | [001, 366] |
%m | 달 | [01, 12] |
%M | 분 | [01, 59] |
%p | AM or PM | AM |
%S | 초 | [00, 61] |
%U | 1년 중 누적 주-일요일을 시작으로 | [00, 53] |
%w | 숫자로 된 요일 | [0(일요일), 6 ] |
%W | 1년 중 누적 주-월요일을 시작으로 | [00, 53] |
%x | 현재 설정된 로케일에 기반한 날짜 출력 | 06/01/01 |
%X | 현재 설정된 로케일에 기반한 시간 출력 | 17:22:21 |
%Y | 년도 출력 | 2001 |
%Z | 시간대 출력 | 대한민국 표준시 |
%% | 문자 | % |
%y | 세기부분을 제외한 년도 출력 | 01 |
import time
time.strftime('%x', time.localtime(time.time()))
'09/27/17'
time.strftime('%c', time.localtime(time.time()))
'Wed Sep 27 06:28:49 2017'
# time.sleep : 주로 루프 안에서 사용하여 일정한 시간 간격을 두고 루프를 실행
import time
for i in range(10):
print(i)
time.sleep(1)
0 1 2 3 4 5 6 7 8 9
import calendar
print(calendar.calendar(2017)) # calendar.prcal(2017)
2017 January February March Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 1 2 3 4 5 1 2 3 4 5 2 3 4 5 6 7 8 6 7 8 9 10 11 12 6 7 8 9 10 11 12 9 10 11 12 13 14 15 13 14 15 16 17 18 19 13 14 15 16 17 18 19 16 17 18 19 20 21 22 20 21 22 23 24 25 26 20 21 22 23 24 25 26 23 24 25 26 27 28 29 27 28 27 28 29 30 31 30 31 April May June Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 1 2 3 4 5 6 7 1 2 3 4 3 4 5 6 7 8 9 8 9 10 11 12 13 14 5 6 7 8 9 10 11 10 11 12 13 14 15 16 15 16 17 18 19 20 21 12 13 14 15 16 17 18 17 18 19 20 21 22 23 22 23 24 25 26 27 28 19 20 21 22 23 24 25 24 25 26 27 28 29 30 29 30 31 26 27 28 29 30 July August September Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 1 2 3 4 5 6 1 2 3 3 4 5 6 7 8 9 7 8 9 10 11 12 13 4 5 6 7 8 9 10 10 11 12 13 14 15 16 14 15 16 17 18 19 20 11 12 13 14 15 16 17 17 18 19 20 21 22 23 21 22 23 24 25 26 27 18 19 20 21 22 23 24 24 25 26 27 28 29 30 28 29 30 31 25 26 27 28 29 30 31 October November December Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 1 2 3 4 5 1 2 3 2 3 4 5 6 7 8 6 7 8 9 10 11 12 4 5 6 7 8 9 10 9 10 11 12 13 14 15 13 14 15 16 17 18 19 11 12 13 14 15 16 17 16 17 18 19 20 21 22 20 21 22 23 24 25 26 18 19 20 21 22 23 24 23 24 25 26 27 28 29 27 28 29 30 25 26 27 28 29 30 31 30 31
calendar.prmonth(2017, 10)
October 2017 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
# calendar.weekday : 그 날짜에 해당하는 요일 정보를 리턴, 0 - 6
calendar.weekday(2017, 9, 27)
2
# calendar.monthrange : 입력받은 달의 1일이 무슨 요일인지와 그 달이 며칠까지 있는지를 튜플 형태로 리턴
calendar.monthrange(2017, 9)
(4, 30)
# random.random : 0.0 에서 1.0 사이의 실수 중에서 난수값을 리턴
import random
random.random()
0.33541440698496394
random.random()
0.6925208291425975
# random.randint : 주어진 정수 중에서 난수값을 리턴
random.randint(1, 10)
9
random.randint(1, 55)
47
import random
def random_pop(data):
number = random.randint(0, len(data)-1)
return data.pop(number)
data = [1, 2, 3, 4, 5]
while data:
print(random_pop(data))
1 3 4 2 5
# random 모듈의 choice 함수를 사용하여 더 직관적으로 표현
def random_pop(data):
number = random.choice(data)
data.remove(number)
return number
data = [1, 2, 3, 4, 5]
while data: print(random_pop(data))
4 3 1 5 2
# random.shuffle : 리스트의 항목을 무작위로 섞어주는 함수
data = [1, 2, 3, 4, 5]
random.shuffle(data)
data
[2, 4, 3, 5, 1]
import webbrowser
webbrowser.open("http://google.com")
webbrowser.open_new("http://google.com")