import string
print dir(string)
print string.__dict__.keys()
['Formatter', 'Template', '_TemplateMetaclass', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_float', '_idmap', '_idmapL', '_int', '_long', '_multimap', '_re', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'atof', 'atof_error', 'atoi', 'atoi_error', 'atol', 'atol_error', 'capitalize', 'capwords', 'center', 'count', 'digits', 'expandtabs', 'find', 'hexdigits', 'index', 'index_error', 'join', 'joinfields', 'letters', 'ljust', 'lower', 'lowercase', 'lstrip', 'maketrans', 'octdigits', 'printable', 'punctuation', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitfields', 'strip', 'swapcase', 'translate', 'upper', 'uppercase', 'whitespace', 'zfill'] ['ascii_lowercase', 'upper', '_re', 'letters', 'atol_error', 'lstrip', 'uppercase', 'ascii_letters', 'find', 'atof', 'replace', 'capwords', 'index_error', 'expandtabs', 'Template', 'strip', 'ascii_uppercase', 'octdigits', 'index', 'ljust', 'whitespace', '_int', 'rindex', '_float', 'punctuation', '__package__', 'printable', 'splitfields', 'split', 'rstrip', 'translate', '__doc__', '_multimap', 'count', 'joinfields', 'rjust', '__builtins__', '__file__', 'lower', 'swapcase', 'atof_error', 'atoi', 'hexdigits', 'Formatter', 'atol', '__name__', 'rsplit', '_idmapL', 'digits', 'lowercase', 'join', 'center', '_long', 'rfind', 'atoi_error', 'maketrans', 'capitalize', '_TemplateMetaclass', 'zfill', '_idmap']
for name, val in string.__dict__.items():
print 'name = %-20s, type = %s' % (name, type(val))
name = ascii_lowercase , type = <type 'str'> name = upper , type = <type 'function'> name = _re , type = <type 'module'> name = letters , type = <type 'str'> name = atol_error , type = <type 'type'> name = lstrip , type = <type 'function'> name = uppercase , type = <type 'str'> name = ascii_letters , type = <type 'str'> name = find , type = <type 'function'> name = atof , type = <type 'function'> name = replace , type = <type 'function'> name = capwords , type = <type 'function'> name = index_error , type = <type 'type'> name = expandtabs , type = <type 'function'> name = Template , type = <class 'string._TemplateMetaclass'> name = strip , type = <type 'function'> name = ascii_uppercase , type = <type 'str'> name = octdigits , type = <type 'str'> name = index , type = <type 'function'> name = ljust , type = <type 'function'> name = whitespace , type = <type 'str'> name = _int , type = <type 'type'> name = rindex , type = <type 'function'> name = _float , type = <type 'type'> name = punctuation , type = <type 'str'> name = __package__ , type = <type 'NoneType'> name = printable , type = <type 'str'> name = splitfields , type = <type 'function'> name = split , type = <type 'function'> name = rstrip , type = <type 'function'> name = translate , type = <type 'function'> name = __doc__ , type = <type 'str'> name = _multimap , type = <type 'classobj'> name = count , type = <type 'function'> name = joinfields , type = <type 'function'> name = rjust , type = <type 'function'> name = __builtins__ , type = <type 'dict'> name = __file__ , type = <type 'str'> name = lower , type = <type 'function'> name = swapcase , type = <type 'function'> name = atof_error , type = <type 'type'> name = atoi , type = <type 'function'> name = hexdigits , type = <type 'str'> name = Formatter , type = <type 'type'> name = atol , type = <type 'function'> name = __name__ , type = <type 'str'> name = rsplit , type = <type 'function'> name = _idmapL , type = <type 'NoneType'> name = digits , type = <type 'str'> name = lowercase , type = <type 'str'> name = join , type = <type 'function'> name = center , type = <type 'function'> name = _long , type = <type 'type'> name = rfind , type = <type 'function'> name = atoi_error , type = <type 'type'> name = maketrans , type = <type 'builtin_function_or_method'> name = capitalize , type = <type 'function'> name = _TemplateMetaclass , type = <type 'type'> name = zfill , type = <type 'function'> name = _idmap , type = <type 'str'>
import mymath
mymath.mypi = 6.2 # 값 수정(원래 모듈 파일에 정의된 값은 3.14)
import mymath # 다시 import
print mymath.mypi # 3.14가 아니라 6.2 -> 즉 이미 적재되어 있는 모듈 그냥 이용
50.24 6.2
print mymath.mypi
reload(mymath)
print mymath.mypi
6.2 50.24 3.14
def f(width, height, **kw):
print width, height
print kw
value = 0
for key in kw:
value += kw[key]
return value
print f(width=10, height=5, depth=10, diamension=3)
10 5 {'depth': 10, 'diamension': 3} 13
print f(10, 5, depth=10, diamension=3)
10 5 {'depth': 10, 'diamension': 3} 13
print f(width=10, height=5, 10, 3)
File "<ipython-input-11-840223010262>", line 1 print f(width=10, height=5, 10, 3) SyntaxError: non-keyword arg after keyword arg
print f(10, 5, 10, 3)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-12-8900a8c061b7> in <module>() ----> 1 print f(10, 5, 10, 3) TypeError: f() takes exactly 2 arguments (4 given)
def g(a, b, k = 1, *args, **kw):
print a, b
print args
print kw
g(1, 2, 3, 4, 5, c=6, d=7)
1 2 (4, 5) {'c': 6, 'd': 7}
def h(a, b, c):
print a, b, c
args = (1, 2, 3)
h(*args)
1 2 3
dargs = {'a':1, 'b':2, 'c':3}
h(**dargs)
1 2 3
args = (1,2)
dargs = {'c':3}
h(*args, **dargs)
1 2 3
def f1(x):
return x*x + 3*x - 10
def f2(x):
return x*x*x
def g(func):
return [func(x) for x in range(-10, 10)]
print g(f1)
print g(f2)
[60, 44, 30, 18, 8, 0, -6, -10, -12, -12, -10, -6, 0, 8, 18, 30, 44, 60, 78, 98] [-1000, -729, -512, -343, -216, -125, -64, -27, -8, -1, 0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
def g(func):
return [func(x) for x in range(-10, 10)]
print g(lambda x: x*x + 3*x - 10)
print g(lambda x: x*x*x)
[60, 44, 30, 18, 8, 0, -6, -10, -12, -12, -10, -6, 0, 8, 18, 30, 44, 60, 78, 98] [-1000, -729, -512, -343, -216, -125, -64, -27, -8, -1, 0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
print [(lambda x: x*x + 3*x - 10)(x) for x in range(-10, 10)]
print [(lambda x: x*x*x)(x) for x in range(-10, 10)]
[60, 44, 30, 18, 8, 0, -6, -10, -12, -12, -10, -6, 0, 8, 18, 30, 44, 60, 78, 98] [-1000, -729, -512, -343, -216, -125, -64, -27, -8, -1, 0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
print map(lambda x: x*x + 3*x - 10, range(-10, 10))
print map(lambda x: x*x*x, range(-10, 10))
[60, 44, 30, 18, 8, 0, -6, -10, -12, -12, -10, -6, 0, 8, 18, 30, 44, 60, 78, 98] [-1000, -729, -512, -343, -216, -125, -64, -27, -8, -1, 0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
Y1 = map(lambda x, y: x + y, [1, 2, 3, 4, 5], [6, 7, 8, 9, 10])
Y2 = map(lambda x, y, z: x + y + z, [1, 2, 3], [4, 5, 6], [7, 8, 9])
print Y1
print Y2
[7, 9, 11, 13, 15] [12, 15, 18]
a = ['a', 'b', 'c', 'd']
print map(None, a)
['a', 'b', 'c', 'd']
a = ['a', 'b', 'c', 'd']
b = [1, 2, 3, 4]
print map(None, a, b)
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
a = ['a', 'b', 'c', 'd']
b = [1, 2, 3, 4]
c = [5, 6, 7, 8]
print map(None, a, b, c)
[('a', 1, 5), ('b', 2, 6), ('c', 3, 7), ('d', 4, 8)]
a = ['a', 'b']
b = [1, 2, 3, 4]
print map(None, a, b)
[('a', 1), ('b', 2), (None, 3), (None, 4)]
a = ['a', 'b']
b = [1, 2, 3, 4]
print zip(a, b)
[('a', 1), ('b', 2)]
print zip([1, 2, 3], [4, 5, 6, 7, 8])
[(1, 4), (2, 5), (3, 6)]
L = ['high', False, 'level', '', 'built-in', '', 'function', 0, 10]
L = filter(None, L)
print L
['high', 'level', 'built-in', 'function', 10]
def f(a, b, c=1):
'func attribute testing'
localx = 1
localy = 2
return 1
print f.__doc__ # 문서 문자열
print f.func_doc
print
print f.__name__ # 함수의 이름
print f.func_name
print
print f.func_defaults # 기본 인수값들
func attribute testing func attribute testing f f (1,)
참고: http://stackoverflow.com/questions/2665866/what-is-the-wb-mean-in-this-code-using-python
s = """Its power: Python developers typically report
they are able to develop applications in a half
to a tenth the amount of time it takes them to do
the same work in such languages as C."""
with open('t.txt', 'w') as f: # f = open('t.txt', 'w')과 동일
f.write(s)
# f.close() 작성할 필요 없음. 자동으로 닫힘
import os
os.chdir('/Users/yhhan/git/python-e-learning')
print os.getcwd()
print
for path, subdirs, files in os.walk(os.getcwd()):
print path, " *** ", subdirs, " *** ", files
f = open('supplement-2016-09.ipynb')
print len(f.read())
f.close()
70122
import os
os.path.getsize('supplement-2016-09.ipynb')
70122
import os
os.linesep
'\n'
f = open('supplement-2016-09.ipynb')
s = f.read()
n = len(s.split())
print n
f.close()
8130
n = len(open('supplement-2016-09.ipynb').read().split())
print n
8130
f = open('supplement-2016-09.ipynb')
s = f.read()
print s.count('\n')
f.close()
2570
f = open('supplement-2016-09.ipynb')
print len(f.readlines())
f.close()
2570
print open('supplement-2016-09.ipynb').read().count('\n')
2570
print len(open('supplement-2016-09.ipynb').readlines())
2570
Mode | 간단 설명 | 자세한 설명 |
---|---|---|
'r' | 읽기 전용(기본 모드) | 파일 객체를 읽기 모드로 생성하고, 파일 포인터를 파일 처음 위치에 놓는다. |
'w' | 쓰기 전용(기존 파일 내용 삭제) | 파일이 존재하지 않으면 새로운 파일을 쓰기 모드로 생성하고, 해당 파일이 이미 존재하면 내용을 모두 없에면서 쓰기 모드로 생성하고, 파일 포인터를 파일 처음 위치에 놓는다. |
'a' | 파일 끝에 추가(쓰기 전용) | 파일이 존재하지 않으면 새롭게 파일을 생성하면서 쓰기 모드로 생성하고, 해당 파일이 이미 존재하면 파일 객체을 쓰기 모드로 생성하면서 파일 포인터를 파일의 마지막 위치에 놓는다 (그래서, 이후 작성되는 내용은 파일의 뒷 부분에 추가). |
'r+' | 읽고 쓰기 | 파일 객체를 읽고 쓸 수 있도록 생성한다. 파일 포인터를 파일 처음 위치에 놓는다. |
'w+' | 읽고 쓰기(기존 파일 내용 삭제) | 파일 객체를 읽고 쓸 수 있도록 생성한다. 파일이 존재하지 않으면 새로운 파일을 생성하고, 해당 파일이 이미 존재하면 내용을 모두 없에면서 생성하고, 파일 포인터를 파일 처음 위치에 놓는다. |
'a+' | 읽고 쓰기(파일 끝에 추가) | 파일 객체를 읽고 쓸 수 있도록 생성한다. 파일이 존재하지 않으면 새롭게 파일을 생성하고, 해당 파일이 이미 존재하면 파일 객체을 생성하면서 파일 포인터를 파일의 마지막 위치에 놓는다 (그래서, 이후 작성되는 내용은 파일의 뒷 부분에 추가). |
Mode | 간단 설명 |
---|---|
'rb' | 이진 파일 읽기 전용 |
'wb' | 이진 파일 쓰기 전용(기존 파일 내용 삭제) |
'ab' | 이진 파일 끝에 추가(쓰기 전용) |
'rb+' | 이진 파일 읽고 쓰기 |
'wb+' | 이진 파일 읽고 쓰기(기존 파일 내용 삭제) |
'ab+' | 이진 파일 끝에 추가(읽기도 가능) |
import random
def getRandomLowerCaseLetter():
return chr(random.randint(ord('a'), ord('z')))
def createList():
'''
소문자를 랜덤하게 생성하여 담은 리스트를 반환한다.
'''
chars = []
for i in range(100):
chars.append(getRandomLowerCaseLetter())
#위 코드는 아래 코드와 동일
#chars = [getRandomLowerCaseLetter() for i in range(100)]
return chars
def displayList(chars):
'''
리스트에 포함된 문자를 한 행에 20개씩 출력한다.
'''
for i in range(len(chars)):
if (i + 1) % 20 == 0:
print chars[i]
else:
print chars[i],
def countLetters(chars):
'''
0으로 초기화된 26개의 정수리스트를 생성한 후 인자로 주어진 chars에 있는 각 문자들의 개수를 저장한다.
'''
counts = [0] * 26
for i in range(len(chars)):
counts[ord(chars[i]) - ord('a')] += 1
return counts
def displayCounts(counts):
'''
각 문자별로 카운트를 한 행에 10개씩 출력한다.
'''
for i in range(len(counts)):
if (i + 1) % 10 == 0:
print chr(i + ord('a')), counts[i]
else:
print chr(i + ord('a')), counts[i],
if __name__ == '__main__':
chars = createList()
displayList(chars)
print
counts = countLetters(chars)
displayCounts(counts)
e d t p p q d e l f q d w x h k r p c h j b a e p x o x z h d t i v w s y r p q e s y d f m e w l r u b l t j s h m r q r n l k g a d o o w r q p b u n e f g d i l g y u l r j z b p o d t u l e o u e a 2 b 4 c 1 d 8 e 8 f 3 g 3 h 4 i 2 j 3 k 2 l 7 m 2 n 2 o 5 p 7 q 5 r 7 s 3 t 4 u 5 v 1 w 4 x 3 y 3 z 2
import random
import time
NUMBER_OF_ELEMENTS = 10000
lst = list(range(NUMBER_OF_ELEMENTS))
random.shuffle(lst)
print lst[0:10]
s = set(lst)
# 해당 원소가 집합/리스트에 포함되어 있는지 검사
startTime = time.time()
for i in range(NUMBER_OF_ELEMENTS):
i in s
endTime = time.time()
runTime = int((endTime - startTime) * 1000)
print 'The elapsed time to check into a set is %s ms' % runTime
startTime = time.time()
for i in range(NUMBER_OF_ELEMENTS):
i in lst
endTime = time.time()
runTime = int((endTime - startTime) * 1000)
print 'The elapsed time to check into a list is %s ms' % runTime
# 해당 원소를 집합/리스트로 부터 제거
startTime = time.time()
for i in range(NUMBER_OF_ELEMENTS):
s.remove(i)
endTime = time.time()
runTime = int((endTime - startTime) * 1000)
print 'The elapsed time to remove each element from a set is %s ms' % runTime
startTime = time.time()
for i in range(NUMBER_OF_ELEMENTS):
lst.remove(i)
endTime = time.time()
runTime = int((endTime - startTime) * 1000)
print 'The elapsed time to remove each element from a list is %s ms' % runTime
[5601, 7177, 661, 7579, 347, 6173, 2121, 4834, 2932, 9408] The elapsed time to check into a set is 4 ms The elapsed time to check into a list is 1204 ms The elapsed time to remove each element from a set is 2 ms The elapsed time to remove each element from a list is 488 ms
# -*-coding:utf-8 -*-
s = "We propose to start by making it possible to teach progra\
mming in python, an existing scripting language, and to focus \
on creating a new development enviroment and teaching \
materials for it."
# 대치 과정
s=s.replace(',','')
s=s.replace('.','')
s=s.lower()
#공백 단위로 단어 쪼개고 단어 넣을 딕셔너리 선언
listSplited = s.split()
words = {}
#단어 쪼개놓은 리스트에서 각각 단어의 개수 세기
for i in listSplited:
if not i in words.keys():
words[i]=1
else:
words[i]=words[i]+1
#포맷을 이용한 출력
format = "%s : %d"
for i in words:
print format % (i, words[i])
and : 2 it : 2 existing : 1 in : 1 for : 1 start : 1 enviroment : 1 to : 3 new : 1 development : 1 we : 1 creating : 1 python : 1 propose : 1 possible : 1 focus : 1 teaching : 1 teach : 1 an : 1 by : 1 a : 1 on : 1 language : 1 programming : 1 materials : 1 making : 1 scripting : 1
a = [1, 2, 3, 4, 5]
b = range(10)
print a
print a[0]
print b
print b[2]
[1, 2, 3, 4, 5] 1 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 2
a = [0] * 10
a
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
mat = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print mat
print mat[1][2]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] 6
다음은 고등학교 수학에서 배운 집합의 표기 방법이다.
파이썬의 리스트 내포(list comprehension)는 바로 위 집합 표기법과 유사한 방식의 리터럴이다.
위 집합들을 리스트 내포 방식으로 표현하면 다음과 같다.
k = [(x,y,z) for x in range(1,30) for y in range(x,30) for z in range(y,30) if x**2 + y**2 == z**2]
print k
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 15, 17), (9, 12, 15), (10, 24, 26), (12, 16, 20), (15, 20, 25), (20, 21, 29)]
l = []
for x in range(1,30):
for y in range(x,30):
for z in range (y, 30):
if x**2 + y**2 == z**2:
l.append((x, y, z))
print l
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 15, 17), (9, 12, 15), (10, 24, 26), (12, 16, 20), (15, 20, 25), (20, 21, 29)]
list_a = ['A', 'B']
list_b = ['C', 'D']
print [x + y for x in list_a for y in list_b]
print
print [[x + y for x in list_a] for y in list_b]
['AC', 'AD', 'BC', 'BD'] [['AC', 'BC'], ['AD', 'BD']]
l = []
for y in list_b:
l2 = []
for x in list_a:
l2.append(x+y)
l.append(l2)
print l
[['AC', 'BC'], ['AD', 'BD']]
mat = [ [0]*4 for x in range(3)]
print mat
mat[0][0] = 100
print mat
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] [[100, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
print __name__ # 로컬 이름
print
print __doc__ # 로컬에 지정된 문서문자열
print
__main__ Automatically created module for IPython interactive environment
import math
print "math.__name__: ", math.__name__
print
print "math.__doc__:", math.__doc__
print
print "math.log10.__name__: ", math.log10.__name__
print
print "math.log10.__doc__: ", math.log10.__doc__
print
print type(math.log10)
math.__name__: math math.__doc__: This module is always available. It provides access to the mathematical functions defined by the C standard. math.log10.__name__: log10 math.log10.__doc__: log10(x) Return the base 10 logarithm of x. <type 'builtin_function_or_method'>
? math.log10
a = unicode("한글과 세종대왕", 'utf-8')
b = u"한글과 세종대왕"
print a == b
print a is b
True False
print ord('A') # ord(): 문자의 ASCII 코드값 반환
print chr(65) # char(): ASCII 코드 65를 지니는 문자를 반환
65 A
print unichr(0xac00) # unichr(): UNICODE 코드 0xac00를 지니는 문자를 반환
print unichr(44032)
가 가
i = 0
while i < 1000:
print unichr(0xac00 + i),
i = i + 1
가 각 갂 갃 간 갅 갆 갇 갈 갉 갊 갋 갌 갍 갎 갏 감 갑 값 갓 갔 강 갖 갗 갘 같 갚 갛 개 객 갞 갟 갠 갡 갢 갣 갤 갥 갦 갧 갨 갩 갪 갫 갬 갭 갮 갯 갰 갱 갲 갳 갴 갵 갶 갷 갸 갹 갺 갻 갼 갽 갾 갿 걀 걁 걂 걃 걄 걅 걆 걇 걈 걉 걊 걋 걌 걍 걎 걏 걐 걑 걒 걓 걔 걕 걖 걗 걘 걙 걚 걛 걜 걝 걞 걟 걠 걡 걢 걣 걤 걥 걦 걧 걨 걩 걪 걫 걬 걭 걮 걯 거 걱 걲 걳 건 걵 걶 걷 걸 걹 걺 걻 걼 걽 걾 걿 검 겁 겂 것 겄 겅 겆 겇 겈 겉 겊 겋 게 겍 겎 겏 겐 겑 겒 겓 겔 겕 겖 겗 겘 겙 겚 겛 겜 겝 겞 겟 겠 겡 겢 겣 겤 겥 겦 겧 겨 격 겪 겫 견 겭 겮 겯 결 겱 겲 겳 겴 겵 겶 겷 겸 겹 겺 겻 겼 경 겾 겿 곀 곁 곂 곃 계 곅 곆 곇 곈 곉 곊 곋 곌 곍 곎 곏 곐 곑 곒 곓 곔 곕 곖 곗 곘 곙 곚 곛 곜 곝 곞 곟 고 곡 곢 곣 곤 곥 곦 곧 골 곩 곪 곫 곬 곭 곮 곯 곰 곱 곲 곳 곴 공 곶 곷 곸 곹 곺 곻 과 곽 곾 곿 관 괁 괂 괃 괄 괅 괆 괇 괈 괉 괊 괋 괌 괍 괎 괏 괐 광 괒 괓 괔 괕 괖 괗 괘 괙 괚 괛 괜 괝 괞 괟 괠 괡 괢 괣 괤 괥 괦 괧 괨 괩 괪 괫 괬 괭 괮 괯 괰 괱 괲 괳 괴 괵 괶 괷 괸 괹 괺 괻 괼 괽 괾 괿 굀 굁 굂 굃 굄 굅 굆 굇 굈 굉 굊 굋 굌 굍 굎 굏 교 굑 굒 굓 굔 굕 굖 굗 굘 굙 굚 굛 굜 굝 굞 굟 굠 굡 굢 굣 굤 굥 굦 굧 굨 굩 굪 굫 구 국 굮 굯 군 굱 굲 굳 굴 굵 굶 굷 굸 굹 굺 굻 굼 굽 굾 굿 궀 궁 궂 궃 궄 궅 궆 궇 궈 궉 궊 궋 권 궍 궎 궏 궐 궑 궒 궓 궔 궕 궖 궗 궘 궙 궚 궛 궜 궝 궞 궟 궠 궡 궢 궣 궤 궥 궦 궧 궨 궩 궪 궫 궬 궭 궮 궯 궰 궱 궲 궳 궴 궵 궶 궷 궸 궹 궺 궻 궼 궽 궾 궿 귀 귁 귂 귃 귄 귅 귆 귇 귈 귉 귊 귋 귌 귍 귎 귏 귐 귑 귒 귓 귔 귕 귖 귗 귘 귙 귚 귛 규 귝 귞 귟 균 귡 귢 귣 귤 귥 귦 귧 귨 귩 귪 귫 귬 귭 귮 귯 귰 귱 귲 귳 귴 귵 귶 귷 그 극 귺 귻 근 귽 귾 귿 글 긁 긂 긃 긄 긅 긆 긇 금 급 긊 긋 긌 긍 긎 긏 긐 긑 긒 긓 긔 긕 긖 긗 긘 긙 긚 긛 긜 긝 긞 긟 긠 긡 긢 긣 긤 긥 긦 긧 긨 긩 긪 긫 긬 긭 긮 긯 기 긱 긲 긳 긴 긵 긶 긷 길 긹 긺 긻 긼 긽 긾 긿 김 깁 깂 깃 깄 깅 깆 깇 깈 깉 깊 깋 까 깍 깎 깏 깐 깑 깒 깓 깔 깕 깖 깗 깘 깙 깚 깛 깜 깝 깞 깟 깠 깡 깢 깣 깤 깥 깦 깧 깨 깩 깪 깫 깬 깭 깮 깯 깰 깱 깲 깳 깴 깵 깶 깷 깸 깹 깺 깻 깼 깽 깾 깿 꺀 꺁 꺂 꺃 꺄 꺅 꺆 꺇 꺈 꺉 꺊 꺋 꺌 꺍 꺎 꺏 꺐 꺑 꺒 꺓 꺔 꺕 꺖 꺗 꺘 꺙 꺚 꺛 꺜 꺝 꺞 꺟 꺠 꺡 꺢 꺣 꺤 꺥 꺦 꺧 꺨 꺩 꺪 꺫 꺬 꺭 꺮 꺯 꺰 꺱 꺲 꺳 꺴 꺵 꺶 꺷 꺸 꺹 꺺 꺻 꺼 꺽 꺾 꺿 껀 껁 껂 껃 껄 껅 껆 껇 껈 껉 껊 껋 껌 껍 껎 껏 껐 껑 껒 껓 껔 껕 껖 껗 께 껙 껚 껛 껜 껝 껞 껟 껠 껡 껢 껣 껤 껥 껦 껧 껨 껩 껪 껫 껬 껭 껮 껯 껰 껱 껲 껳 껴 껵 껶 껷 껸 껹 껺 껻 껼 껽 껾 껿 꼀 꼁 꼂 꼃 꼄 꼅 꼆 꼇 꼈 꼉 꼊 꼋 꼌 꼍 꼎 꼏 꼐 꼑 꼒 꼓 꼔 꼕 꼖 꼗 꼘 꼙 꼚 꼛 꼜 꼝 꼞 꼟 꼠 꼡 꼢 꼣 꼤 꼥 꼦 꼧 꼨 꼩 꼪 꼫 꼬 꼭 꼮 꼯 꼰 꼱 꼲 꼳 꼴 꼵 꼶 꼷 꼸 꼹 꼺 꼻 꼼 꼽 꼾 꼿 꽀 꽁 꽂 꽃 꽄 꽅 꽆 꽇 꽈 꽉 꽊 꽋 꽌 꽍 꽎 꽏 꽐 꽑 꽒 꽓 꽔 꽕 꽖 꽗 꽘 꽙 꽚 꽛 꽜 꽝 꽞 꽟 꽠 꽡 꽢 꽣 꽤 꽥 꽦 꽧 꽨 꽩 꽪 꽫 꽬 꽭 꽮 꽯 꽰 꽱 꽲 꽳 꽴 꽵 꽶 꽷 꽸 꽹 꽺 꽻 꽼 꽽 꽾 꽿 꾀 꾁 꾂 꾃 꾄 꾅 꾆 꾇 꾈 꾉 꾊 꾋 꾌 꾍 꾎 꾏 꾐 꾑 꾒 꾓 꾔 꾕 꾖 꾗 꾘 꾙 꾚 꾛 꾜 꾝 꾞 꾟 꾠 꾡 꾢 꾣 꾤 꾥 꾦 꾧 꾨 꾩 꾪 꾫 꾬 꾭 꾮 꾯 꾰 꾱 꾲 꾳 꾴 꾵 꾶 꾷 꾸 꾹 꾺 꾻 꾼 꾽 꾾 꾿 꿀 꿁 꿂 꿃 꿄 꿅 꿆 꿇 꿈 꿉 꿊 꿋 꿌 꿍 꿎 꿏 꿐 꿑 꿒 꿓 꿔 꿕 꿖 꿗 꿘 꿙 꿚 꿛 꿜 꿝 꿞 꿟 꿠 꿡 꿢 꿣 꿤 꿥 꿦 꿧
f = 1.23456789123456789
print f
print str(f)
print repr(f) # repr()은 유효 숫자를 길게 출력
1.23456789123 1.23456789123 1.234567891234568
print "%s, %r" % (f, f) # str()과 repr() 호출
1.23456789123, 1.234567891234568
print "%s -- %s" % ((1, 2), [3, 4, 5]) # str() 호출
(1, 2) -- [3, 4, 5]
print "%r -- %r" % ((1, 2), [3, 4, 5]) # str() 대신에 repr() 내장 함수 사용
(1, 2) -- [3, 4, 5]
g = 0.3
print str(g)
print repr(g)
0.3 0.3
h = 'Hello'
print str(h)
print repr(h)
Hello 'Hello'
x = eval(str(h))
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-12-282822699c67> in <module>() ----> 1 x = eval(str(h)) <string> in <module>() NameError: name 'Hello' is not defined
x = eval(repr(h))
a = '1 + 2 + 3'
b = eval(a)
print b
6
def add(a, b):
"add(a, b) returns a+b"
return a + b
print add.__doc__
add(a, b) returns a+b
help(add)
Help on function add in module __main__: add(a, b) add(a, b) returns a+b
? add
import string
print string.digits
print string.octdigits
print string.hexdigits
print string.letters
print string.lowercase
print string.uppercase
print string.punctuation # 각종 기호들
print
print string.printable # 인쇄 가능한 모든 문자들
print string.whitespace # 공백 문자들 '\011\012\013\014\015'
0123456789 01234567 0123456789abcdefABCDEF ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
x = 'a'
print x in string.uppercase
print x in string.lowercase
False True
d = string.letters + string.digits
print d
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
userid = raw_input('your id:')
your id:3##
d = string.letters + string.digits
for ch in userid:
if ch not in d:
print 'invalid user id'
break
invalid user id
import time
start_time = time.time()
s = ''
for k in range(1000000):
s += 'python'
end_time = time.time()
print end_time - start_time
0.534403085709
start_time = time.time()
t = []
for k in range(1000000):
t.append('python')
s = ''.join(t)
end_time = time.time()
print end_time - start_time
0.396770954132
start_time = time.time()
s = 'python' * 1000000
end_time = time.time()
print end_time - start_time
0.00274300575256
print 5 / 4 # 자동으로 floor 처리 됨
print 5.0 / 4
print
print -5 / 4 # 자동으로 floor 처리 됨
print -5.0 / 4
1 1.25 -2 -1.25
print 1.0 / 2
print 1.0 // 2 # floor division
print
print 5.0 / 4
print 5.0 // 4 # floor division
print 5 / 4
print 5 // 4 # floor division
print
print -5.0 / 4
print -5.0 // 4 # floor division
print -5 / 4
print -5 // 4 # floor division
0.5 0.0 1.25 1.0 1 1 -1.25 -2.0 -2 -2
def incr(x=1, y): # 디폴트 인자 뒤에 정상적인 인자 선언 안됨
return x + y
print incr(5)
print incr(5, 10)
File "<ipython-input-24-e4dbb7c32e28>", line 1 def incr(x=1, y): # 디폴트 인자 뒤에 정상적인 인자 선언 안됨 SyntaxError: non-default argument follows default argument
import time
currentTime = time.time() # Unix Epoch 부터 현재까지 경과된 시각 (GMT/UST 기준)을 실수형 초 단위로 최대한 정확하게 얻어온다.
print currentTime
print type(currentTime)
print
totalSeconds = int(currentTime) # 1970년 1월 1일 0시 이후부터 현재시각까지의 정수형 초 값을 얻어온다.
print "totalSeconds -", totalSeconds
currentSecond = totalSeconds % 60 # 현재 시각의 초 값을 얻어온다.
totalMinutes = totalSeconds // 60 # 전체 분 값을 계산한다.
print "totalMinutes -", totalMinutes
currentMinute = totalMinutes % 60 # 현재 시각의 분 값을 얻어온다.
totalHours = totalMinutes // 60 # 전체 시 값을 계산한다.
print "totalHours -", totalHours
currentHours = totalHours % 24 # 현재 시각의 시 값을 얻어온다.
print "현재 시각은", currentHours, ":", currentMinute, ":", currentSecond, "GMT 입니다."
1475076684.95 <type 'float'> totalSeconds - 1475076684 totalMinutes - 24584611 totalHours - 409743 현재 시각은 15 : 31 : 24 GMT 입니다.
print time.tzname
print
localtime = time.localtime()
print localtime
('KST', 'KST') time.struct_time(tm_year=2016, tm_mon=9, tm_mday=29, tm_hour=0, tm_min=31, tm_sec=19, tm_wday=3, tm_yday=273, tm_isdst=0)
# This is a guess the number game.
import random
guessesTaken = 0
print('Hello! What is your name?')
myName = raw_input()
number = random.randint(1, 20) # return random integer in range [a, b], including both end points.
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
while guessesTaken < 6:
print('Take a guess.')
guess = int(input())
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
Hello! What is your name? YHHAN Well, YHHAN, I am thinking of a number between 1 and 20. Take a guess. 10 Your guess is too low. Take a guess. 15 Good job, YHHAN! You guessed my number in 2 guesses!
import types
dir(types)
['BooleanType', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', 'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType', 'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType', 'GetSetDescriptorType', 'InstanceType', 'IntType', 'LambdaType', 'ListType', 'LongType', 'MemberDescriptorType', 'MethodType', 'ModuleType', 'NoneType', 'NotImplementedType', 'ObjectType', 'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType', 'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRangeType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__']
print type(123) is types.IntType
print type(123.0) is types.FloatType
print type('abc') is types.StringType
print type([]) is types.ListType
print type(()) is types.TupleType
print type({}) is types.DictionaryType
True True True True True True
x = y = z = 100
del x
y = 200
z = 300
import sys
a1 = 191919
print sys.getrefcount(a1) # 새로운 191919 객체를 만들고 이 객체에 대한 reference count 반환
print
a2 = a1
print sys.getrefcount(a1) # a1과 a3가 참조하는 객체는 동일하며, reference count는 기존보다 1이 증가되어 있음
print sys.getrefcount(a2) # a2는 여전히 reference count가 이전 값과 동일함
print
aa1 = aa2 = aa3 = 202020
print sys.getrefcount(aa1)
print sys.getrefcount(aa2)
print sys.getrefcount(aa3)
3 4 4 5 5 5
import turtle
t = turtle.Turtle()
t.shape("turtle")
t.color("blue")
t.pensize(3) # 펜 사이즈를 3으로 설정한다.
t.penup() # 펜을 종이로 부터 들어올린다.
t.goto(-200, -50) # 해당 좌표로 이동한다.
t.pendown() # 펜을 종이에 놓는다.
t.circle(40, steps=3) # 반지름이 40인 원을 3 step으로만 그린다. ==> 삼각형이 그려짐
t.penup()
t.goto(-100, -50)
t.pendown()
t.circle(40, steps=4)
t.penup()
t.goto(0, -50)
t.pendown()
t.circle(40, steps=5)
t.penup()
t.goto(100, -50)
t.pendown()
t.circle(40, steps=6)
t.penup()
t.goto(200, -50)
t.pendown()
t.circle(40, steps=40)
메소드 명 | 설명 |
---|---|
turtle.pendown() | 펜을 내려놓는다 - 움직일 때 그려진다. |
turtle.penup() | 펜을 들어올린다 - 움직일 때 그려지지 않는다. |
turtle.pensize() | 선의 두께를 특정 폭으로 설정한다. |
메소드 명 |
설명 |
---|---|
turtle.forward(d) | turtle이 향하고 있는 방향으로 특정 거리 d만큼 앞으로 이동시킨다. |
turtle.backward(d) | turtle이 향하고 있는 반대 방향으로 특정 거리 d만큼 뒤로 이동시킨다. turtle의 방향은 바뀌지 않는다. |
turtle.right(angle) | turtle을 특정 각만큼 오른쪽으로 회전시킨다. |
turtle.left(angle) | turtle을 특정 각만큼 왼쪽으로 회전시킨다. |
turtle.goto(x,y) | turtle을 절대 위치 (x,y)로 옮긴다. |
turtle.setx(x) | turtle의 x 좌표를 특정 위치로 옮긴다. |
turtle.setx(y) | turtle의 y 좌표를 특정 위치로 옮긴다. |
turtle.setheading(angle) | 특정 각도로 turtle의 방향을 설정한다. 0-동쪽, 90-북쪽, 180-서쪽, 270-남쪽. |
turtle.home() | turtle을 원점 (0,0)으로 옮기고 동쪽 방향으로 설정한다. |
turtle.circle(r, ext, steps) | 특정 반지름 r, 경계 ext와 단계 step인 원을 그린다. |
turtle.dot(diameter, color) | 특정 지름 diameter와 색상 color인 원을 그린다. |
turtle.undo() | turtle의 마지막 명령을 (반복적으로)되돌린다. |
turtle.speed(s) | 1부터 10사이의 정수(10이 최대) s로 turtle의 속도를 설정한다. |
메소드 명 |
설명 |
---|---|
turtle.color(c) | 펜 색상을 c로 설정한다. |
turtle.fillcolor(c) | 펜 채우기 색상을 c로 설정한다. |
turtle.begin_fill() | 도형을 채우기 전에 이 메소드를 호출한다. |
turtle.end_fill() | begin_fill에 대한 마지막 호출전까지 그려진 도형을 채운다. |
turtle.filling() | 채우기 상태를 반환한다. 채우기 상태이면 True, 그렇지 않으면 False |
turtle.clear() | 창을 깨끗하게 지운다. turtle의 상태와 위치는 영향을 받지 않는다. |
turtle.reset() | 창을 깨끗하게 지우고 turtle의 상태와 위치를 원래 기본값으로 재설정한다. |
turtle.screensize(w,h) | 캔버스의 폭과 높이를 w와 h로 설정한다. |
turtle.hideturtle() | turtle을 보이지 않게 만든다. |
turtle.showturtle() | turtle을 보이게 만든다. |
turtle.isvisible() | turtle이 보이면 True를 반환한다. |
turtle.write(s,font=("Arial",8,"normal")) | 현재 turtle의 위치에 문자열 s를 쓴다. 폰트는 폰트명, 폰트크기, 폰트유형의 세 값으로 구성된다. |
(1) 다음 사항을 읽고 요구하는 프로그램을 작성하시오.
정다각형은 모든 변의 길이와 내각의 크기가 같은 $n$개의 변으로 이루어진 다각형이다 (즉, 다각형이 등변이고 등각이다).
한변의 길이가 $s$일 때 정다각형의 넓이를 계산하는 공식은 다음과 같다.
사용자로 부터 정다각형의 변의 개수와 변의 길이를 입력받고 정다각형의 넓이를 출력하는 프로그램을 작성하시오.
출력예는 다음과 같다.
[출력예]
변의 개수를 입력하세요: 5
변의 길이를 입력하세요: 6.5
다각형의 넓이는 73.69017017488385 입니다.
(2) 다음 사항을 읽고 요구하는 프로그램을 작성하시오.
사용자로 부터 ASCII 코드 (0부터 127 사이의 정수)를 입력받는다.
입력받은 코드에 대한 문자를 출력하는 프로그램을 작성하시오.
출력예는 다음과 같다.
[출력예]
ASCII코드를 입력하세요: 69
문자는 E 입니다.
import math
def distance( x0, y0, x1, y1 ):
"""( x0, y0 )와 ( x1, y1 ) 사이의 거리를 계산한다."""
return math.sqrt( (x1-x0) ** 2 + (y1-y0) ** 2 )
def close( left, right ):
"""두 부동소수점 값이 근사한지 테스트 한다."""
return abs( left - right ) < 1.0e-6
def test_distance():
"""distance 함수가 올바르게 동작하는지 테스트 한다."""
assert close( distance( 1.0, 0.0, 1.0, 0.0 ), 0.0 ), '동일 지점 실패'
assert close( distance( 0.0, 0.0, 1.0, 0.0 ), 1.0 ), '단위 거리 실패'
test_distance()
dir() 내장 함수 사용
아래 리스트 중 python 기본 이름
나머지는 ipython이 자체적으로 생성한 이름들
dir()
['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__name__', '_dh', '_i', '_i1', '_ih', '_ii', '_iii', '_oh', '_sh', 'exit', 'get_ipython', 'quit']
a = 10
print dir(a)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
print dir(__builtin__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__IPYTHON__', '__IPYTHON__active', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'dreload', 'enumerate', 'eval', 'execfile', 'file', 'filter', 'float', 'format', 'frozenset', 'get_ipython', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']
import sys
print sys.version
print
print sys.path
2.7.9 | 64-bit | (default, Jun 30 2015, 22:40:22) [GCC 4.1.2 20080704 (Red Hat 4.1.2-55)] ['', '/home/goslim/Canopy/appdata/canopy-1.5.5.3123.rh5-x86_64/lib/python27.zip', '/home/goslim/Canopy/appdata/canopy-1.5.5.3123.rh5-x86_64/lib/python2.7', '/home/goslim/Canopy/appdata/canopy-1.5.5.3123.rh5-x86_64/lib/python2.7/plat-linux2', '/home/goslim/Canopy/appdata/canopy-1.5.5.3123.rh5-x86_64/lib/python2.7/lib-tk', '/home/goslim/Canopy/appdata/canopy-1.5.5.3123.rh5-x86_64/lib/python2.7/lib-old', '/home/goslim/Canopy/appdata/canopy-1.5.5.3123.rh5-x86_64/lib/python2.7/lib-dynload', '/home/goslim/Enthought/Canopy_64bit/User/lib/python2.7/site-packages', '/home/goslim/Canopy/appdata/canopy-1.5.5.3123.rh5-x86_64/lib/python2.7/site-packages', '/home/goslim/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/IPython/extensions']
print dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_home', '_mercurial', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'exitfunc', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'ps3', 'py3kwarning', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions']
import math
x1 = 10
y1 = 20
x2 = 30
y2 = 40