import keyword
print keyword.kwlist
print
print len(keyword.kwlist)
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield'] 31
str(12345)
'12345'
str = 'abc'
str(12345)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-783964495548> in <module>() 1 str = 'abc' 2 ----> 3 str(12345) TypeError: 'str' object is not callable
#이것은 주석입니다.
import sys #이것도 주석입니다.
if (a == 1) and
File "<ipython-input-11-61e6eb328bcc>", line 1 if (a == 1) and ^ SyntaxError: invalid syntax
a = 1
b = 3
if (a == 1) and \
(b == 3):
print 'connected lines'
connected lines
a = 1
b = a
1 + 3 = a
File "<ipython-input-15-3aa35fdab4b7>", line 1 1 + 3 = a SyntaxError: can't assign to operator
a = 1
a = a + 1
4 == 5
False
4 == 4
True
c, d = 3, 4
x = y = z = 0
e = 3.5; f = 5.6
print a, b, c, d, e, f
1 1 3 4 3.5 5.6
e, f = f, e
print e, f
5.6 3.5
a = (b = c + d)
File "<ipython-input-29-79d71c957091>", line 1 a = (b = c + d) ^ SyntaxError: invalid syntax
a = 1
type(a)
int
a = 'dynamic'
type(a)
str
a = 1
a += 4
a
5
a -= 3
a
2
a *= 2+3
a
10
a = [1,2,3]
b = [10, a, 20]
c = ['x', a, 'y']
print a
print b
print c
[1, 2, 3] [10, [1, 2, 3], 20] ['a', [1, 2, 3], 'b']
a[1] = 1000
print a
print b
print c
[1, 1000, 3] [10, [1, 1000, 3], 20] ['a', [1, 1000, 3], 'b']
a = 1
a = eval('a + 4')
a
5
eval('a = a + 4')
File "<string>", line 1 a = a + 4 ^ SyntaxError: invalid syntax
a = 5
exec('a = a + 4')
a
9
a = 5
exec 'a = a + 4'
a
9
s = '''
a = 1
if a > 0 :
print 'Success'
'''
exec(s)
Success
code = compile('a + 1', '<string>', 'eval')
print type(code)
a = 1
for k in range(10):
a = eval(code)
a
<type 'code'>
11
code = compile('a = a + 1', '<string>', 'single')
a = 1
for k in range(10):
exec(code)
a
11
s = '''
a = 1
for k in range(10):
a = a + 1
print a
'''
code = compile(s, '<string>', 'exec')
exec(code)
11
name = raw_input('name?')
name?이강성
print name
이강성
k = int(raw_input('int : '))
int : 89
k
89
i = input('int :')
int :45
i
45
k = input('expr:')
expr:30+50
k
80
print 4+5, 4-2
9 2
print 1; print 2
1 2
print 1,; print 2
1 2
print 12 + 'spam'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-71-84ee898a197b> in <module>() ----> 1 print 12 + 'spam' TypeError: unsupported operand type(s) for +: 'int' and 'str'
print '12' + 'spam'
12spam
import pprint
complicated = ['spam', (1,2,3), ('hanm', 'egg', ('ab', 'cd', ('abc', 'def')))]
complicated = complicated * 3
pprint.pprint(complicated)
['spam', (1, 2, 3), ('hanm', 'egg', ('ab', 'cd', ('abc', 'def'))), 'spam', (1, 2, 3), ('hanm', 'egg', ('ab', 'cd', ('abc', 'def'))), 'spam', (1, 2, 3), ('hanm', 'egg', ('ab', 'cd', ('abc', 'def')))]
print complicated
['spam', (1, 2, 3), ('hanm', 'egg', ('ab', 'cd', ('abc', 'def'))), 'spam', (1, 2, 3), ('hanm', 'egg', ('ab', 'cd', ('abc', 'def'))), 'spam', (1, 2, 3), ('hanm', 'egg', ('ab', 'cd', ('abc', 'def')))]
complicated
['spam', (1, 2, 3), ('hanm', 'egg', ('ab', 'cd', ('abc', 'def'))), 'spam', (1, 2, 3), ('hanm', 'egg', ('ab', 'cd', ('abc', 'def'))), 'spam', (1, 2, 3), ('hanm', 'egg', ('ab', 'cd', ('abc', 'def')))]
print 'Hello World!'
print "Hello World!"
Hello World! Hello World!
s = "Hello world!"
print s[0]
print s[1]
print s[-1]
print s[-2]
H e ! d
s = "Hello world!"
print s[1:3]
print s[0:5]
el Hello
s = 'Hello'
print s[1:]
print s[:3]
print s[:]
ello Hel Hello
s = 'abcd'
print s[::2]
print s[::-1]
ac dcba
print 'Hello' + '' + 'World'
print 'Hello' * 3
print '-' * 60
HelloWorld HelloHelloHello ------------------------------------------------------------
s = 'Hello World'
s[0] = 'h'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-88-28020f3d59a5> in <module>() 1 s = 'Hello World' ----> 2 s[0] = 'h' TypeError: 'str' object does not support item assignment
s = 'Hello World'
s = 'h' + s[1:]
s
'hello World'
s = 'Hello World'
len(s)
11
s = 'Hello World'
print 'World' in s
print 'World' not in s
True False
L = [1,2,3]
print type(L)
print
print len(L)
print
print L[1]
print L[-1]
print L[1:3]
print
print L + L
print L * 3
<type 'list'> 3 2 3 [2, 3] [1, 2, 3, 1, 2, 3] [1, 2, 3, 1, 2, 3, 1, 2, 3]
L = range(10)
print L
print L[::2]
print L[::-1]
print 4 in L
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 2, 4, 6, 8] [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] True
L = [1,2,3]
L.append(4)
print L
print
del L[0]
print L
print
L.reverse()
print L
print
L.append(5)
print L
L.sort()
print L
[1, 2, 3, 4] [2, 3, 4] [4, 3, 2] [4, 3, 2, 5] [2, 3, 4, 5]
t = (1,2,3)
print len(t)
print
print t[0]
print t[-1]
print t[0:2]
print t[::2]
print
print t + t + t
print t * 3
print
print 3 in t
3 1 3 (1, 2) (1, 3) (1, 2, 3, 1, 2, 3, 1, 2, 3) (1, 2, 3, 1, 2, 3, 1, 2, 3) True
t = (1,2,3)
t[0] = 100
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-105-b050fc22719c> in <module>() 1 t = (1,2,3) 2 ----> 3 t[0] = 100 TypeError: 'tuple' object does not support item assignment
L = [1,2,3]
L[0] = 100
print L
[100, 2, 3]
d = {'one': 'hana', 'two': 'dul', 'three': 'set'}
print d['one']
hana
d = {'one': 'hana', 'two': 'dul', 'three': 'set'}
d['four'] = 'net' # 새 항목의 삽입
print d
d['one'] = 1 # 기존 항목의 값 변경
print d
print 'one' in d # 키에 대한 멤버쉽 테스트
{'four': 'net', 'three': 'set', 'two': 'dul', 'one': 'hana'} {'four': 'net', 'three': 'set', 'two': 'dul', 'one': 1} True
d = {'one': 1, 'two': 'dul', 'three': 'set', 'four': 'net'}
print d.keys() # 키만 리스트로 추출함
print d.values() # 값만 리스트로 추출함
print d.items() # 키와 값의 튜플을 리스트로 반환함
['four', 'three', 'two', 'one'] ['net', 'set', 'dul', 1] [('four', 'net'), ('three', 'set'), ('two', 'dul'), ('one', 1)]
자료형 | 저장/접근 방법 | 변경 가능성 | 저장 모델 |
---|---|---|---|
수치형 | 직접(Direct) | 변경불가능(Immutable) | 리터럴 (Literal) |
문자열 | 시퀀스 (Sequence) | 변경불가능(Immutable) | 리터럴 (Literal) |
리스트 | 시퀀스 (Sequence) | 변경가능(Mutable) | 컨테이너 (Container) |
튜플 | 시퀀스 (Sequence) | 변경불가능(Immutable) | 컨테이너 (Container) |
사전 | 매핑 (Mapping) | 변경가능(Mutable) | 컨테이너 (Container) |
s = [1,2,3]
s[1] = 10
s
[1, 10, 3]
s = (1,2,3)
s[1] = 10
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-118-eb1fdc4c7dc3> in <module>() 1 s = (1,2,3) ----> 2 s[1] = 10 TypeError: 'tuple' object does not support item assignment
x = 1
x = 2
l1 = [1,2,3]
l1 = [4,5,6]
l1 = [4,5,6]
l1[0] = 10
print type(3) #정수
<type 'int'>
print type(3.3) #실수
<type 'float'>
print type('abc') #문자열
<type 'str'>
print type(None) #None 객체, 아무 값도 없다(혹은 아니다)를 나타내는 객체
print
a = None
print a
print type(a)
<type 'NoneType'> None <type 'NoneType'>
print type([]) #리스트
<type 'list'>
print type(()) #튜플
<type 'tuple'>
print type({}) #사전(dict)
<type 'dict'>
print type(type({})) #'type'형
<type 'type'>
a = 0
L = [1,2,3]
print type(a) == type(0)
print type(L) == type([])
print type(L[0]) == type(0)
True True True
import types
print 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', '__builtins__', '__doc__', '__file__', '__name__', '__package__']
from types import *
print type(123) == IntType
print type('abc') == StringType
True True
x = y = z = 100
del x
y = 200
z = 300
import sys
aaa = 191919
print sys.getrefcount(aaa)
bbb = object()
print sys.getrefcount(bbb)
print sys.getrefcount('foobar')
3 2 3
a = 500
b = a
print id(a)
print id(b)
print
x = 1
y = 1
print id(x)
print id(y)
4478569376 4478569376 4298182776 4298182776
c = [1,2,3]
d = [1,2,3]
print c is d
a = 500
b = a
print a is b
x = 1
y = 1
print x is y
e = f = [4,5,6]
print e is f
False True True True
c = [1,2,3]
d = [1,2,3]
c == d
True
if 조건식1:
statements
elif 조건식2:
statements
elif 조건식3:
statements
else:
statements
score = 90
if score >= 90:
print 'Congratulations!!! '
Congratulations!!!
a = 10
if a > 5:
print 'Big'
else:
print 'Small'
Big
a = 10
if a > 5: print 'Big'
else: print 'Small'
Big
n = -2
if n > 0:
print 'Positive'
elif n < 0:
print 'Negative'
else:
print 'Zero'
Negative
order = 'spagetti'
if order == 'spam':
price = 500
elif order == 'ham':
price = 700
elif order == 'egg':
price = 300
elif order == 'spagetti':
price = 900
print price
900
order = 'spagetti'
menu = {'spam':500, 'ham':700, 'egg':300, 'spagetti':900}
price = menu[order]
print price
900
a = 1 # 성공
a = 1 # 실패
File "<ipython-input-160-0453a5e2fe16>", line 2 a = 1 # 실패 ^ IndentationError: unexpected indent
if a > 1:
print 'big'
print 'really?'
File "<ipython-input-161-96672a766929>", line 3 print 'really?' ^ IndentationError: unexpected indent
a = ['cat', 'cow', 'tiger']
for x in a:
print len(x), x
3 cat 3 cow 5 tiger
for x in [1,2,3]:
print x,
1 2 3
print range(10)
for x in range(10):
print x,
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 0 1 2 3 4 5 6 7 8 9
sum = 0
for x in range(1, 11):
sum = sum + x
print sum
55
prod = 1
for x in range(1, 11):
prod = prod * x
prod
3628800
l = ['cat', 'dog', 'bird', 'pig']
for k, animal in enumerate(l):
print k, animal
0 cat 1 dog 2 bird 3 pig
t = ('cat', 'dog', 'bird', 'pig')
for k, animal in enumerate(t):
print k, animal
0 cat 1 dog 2 bird 3 pig
d = {'c':'cat', 'd':'dog', 'b':'bird', 'p':'pig'}
for k, key in enumerate(d):
print k, key, d[key]
0 p pig 1 c cat 2 b bird 3 d dog
for x in range(10):
if x > 3: break
print x
print 'done'
0 1 2 3 done
for x in range(10):
if x < 8: continue
print x
print 'done'
8 9 done
for x in range(10):
print x, # 콤마(,) 때문에 줄이 바뀌지 않는다.
else:
print 'else block'
print 'done'
0 1 2 3 4 5 6 7 8 9 else block done
for x in range(10):
break
print x,
else:
print 'else block'
print 'done'
done
for x in range(2, 4):
for y in range(2, 10):
print x, '*', y, '=', x*y
print
2 * 2 = 4 2 * 3 = 6 2 * 4 = 8 2 * 5 = 10 2 * 6 = 12 2 * 7 = 14 2 * 8 = 16 2 * 9 = 18 3 * 2 = 6 3 * 3 = 9 3 * 4 = 12 3 * 5 = 15 3 * 6 = 18 3 * 7 = 21 3 * 8 = 24 3 * 9 = 27
count = 1
while count < 11:
print count
count = count + 1
1 2 3 4 5 6 7 8 9 10
sum = 0
a = 0
while a < 10:
a = a + 1
sum = sum + a
print sum
55
x = 0
while x < 10:
print x, # 콤마(,) 때문에 줄이 바뀌지 않는다.
x = x + 1
else:
print 'else block'
print 'done'
0 1 2 3 4 5 6 7 8 9 else block done
x = 0
while x < 10:
break
print x,
x = x + 1
else:
print 'else block'
print 'done'
done
x = 0
while x < 10:
if x < 8:
x = x + 1
continue
else:
print x,
x = x + 1
print 'done'
8 9 done
def add(a, b):
return a + b
print add(3, 4)
print add([1,2,3], [4,5,6])
7 [1, 2, 3, 4, 5, 6]
def minus(a, b):
return a - b
print minus(a=12, b=20)
print minus(b=20, a=12)
-8 -8
def incr(x, y=1):
return x + y
print incr(5)
print incr(5, 10)
6 15