import math
x1 = (-b + math.sqrt(b*b - 4*a*c)) / (2.0*a)
x2 = (-b - math.sqrt(b*b - 4*a*c)) / (2.0*a)
D = b*b - 4*a*c
a2 = 2 * a
sd = math.sqrt(D)
x1 = (-b + sd) / a2
x2 = (-b - sd) /a2
def add(a, b):
return a+b
print add(1, 2)
print
def myabs(x):
if x < 0 : x = -x
return x
print abs(-4)
print myabs(-4)
3 4 4
def addabs(a, b):
c = add(a, b)
return myabs(c)
addabs(-5, -7)
12
def add(a, b):
return a+b
add
<function __main__.add>
c = add(10, 30)
print c
40
40 + add(5,10)
55
f = add
print f(4, 5)
9
print f
print f is add
<function add at 0x10b5ad758> True
def simple():
pass
simple()
def addmember(memberlist, newmember):
if newmember not in memberlist: # 기존 멤버가 아니면
memberlist.append(newmember) # 추가
#리스트에 초기 멤버 설정
members = ['kim', 'lee', 'park', 'youn']
# 새로운 멤버 추가
addmember(members, 'jo')
# (이미 존재하는) 새로운 멤버 추가
addmember(members, 'kim')
print members
['kim', 'lee', 'park', 'youn', 'jo']
def addmember(memberlist, newmembers):
if type(newmembers) not in (type([]), type(())):
newmembers = [newmembers]
for m in newmembers:
if m not in memberlist: #기존 멤버가 아니면
memberlist.append(m) #추가!
members = ['kim', 'lee', 'park', 'youn']
addmember(members, 'jung')
print members
addmember(members, 'lee')
print members
addmember(members, ['kim', 'jo', 'jae'])
print members
addmember(members, ('sang', 'oh', 'jae'))
print members
['kim', 'lee', 'park', 'youn', 'jung'] ['kim', 'lee', 'park', 'youn', 'jung'] ['kim', 'lee', 'park', 'youn', 'jung', 'jo', 'jae'] ['kim', 'lee', 'park', 'youn', 'jung', 'jo', 'jae', 'sang', 'oh']
def f1(b):
b = 100
a = 200
f1(a)
print a
200
def f2(b):
b = "abc"
a = "def"
f2(a)
print a
def
def f3(b):
b = (1,2,3)
a = (4,5,6)
f3(a)
print a
(4, 5, 6)
def f4(b):
b[1] = 10
a = [4,5,6]
f4(a)
print a
[4, 10, 6]
def f5(b):
b['a'] = 10
a = {"a":1, "b":2}
f5(a)
print a
{'a': 10, 'b': 2}
def f6(b):
b = [1, 2, 3]
b[1] = 10
a = [4,5,6]
f6(a)
print a
[4, 5, 6]
def nothing():
return
print nothing()
None
def f():
return
f()
a = f()
print a
None
def print_menu():
print '1. Snack'
print '2. Snake'
print '3. Snick'
print_menu()
1. Snack 2. Snake 3. Snick
a = print_menu()
print a
1. Snack 2. Snake 3. Snick None
def abs(x):
if x < 0 : return -x
return x
print abs(-10)
10
def swap(x, y):
return y, x # 튜플로 리턴된다.
a = 10
b = 20
print a, b
print
a, b = swap(a, b) # 결과적으로 a, b = b, a와 동일
print a, b
print
a = 10
b = 20
x = swap(a, b)
print x[0], x[1] # 하나의 이름으로 튜플을 받아서 처리할 수 도있다.
10 20 20 10 20 10
print divmod(9, 5)
print
a, b = divmod(9, 5)
print a, b
(1, 4) 1 4
def length_list(l):
res = []
for el in l:
res.append(len(el))
return res
l = ['python', 'pyson', 'pythong', 'pydon']
print length_list(l)
[6, 5, 7, 5]
l = ['python', 'pyson', 'pythong', 'pydon']
print [len(s) for s in l]
[6, 5, 7, 5]
def add(a, b):
return a + b
c = add(1, 3.4)
d = add('dynamic', 'typing')
e = add(['list'], ['and', 'list'])
print c
print d
print e
4.4 dynamictyping ['list', 'and', 'list']
class MyClass:
def __add__(self, b):
return 'add %s is called' % b
c = MyClass()
print c + 1
print
print c + 'abc'
print
print c + 'anaconda'
add 1 is called add abc is called add anaconda is called
# g, h는 전역 변수
g = 10
h = 5
def f(a): # a는 지역 변수
h = a + 10 # h는 지역, 새로 l-value로 정의했음
b = h + a + g # b도 지역, g는 r-value이므로 기존 값을 참조 - 전역 변수
return b
print f(h) # 함수 호출시에 사용되는 변수는 해당 위치의 스코프에서 값을 찾음 - 전역 변수
print h # 전역 변수 h는 변함 없음
30 5
h = 5
def f(a): # a는 지역
global h # h 변수를 전역이라고 미리 선언함
h = a + 10 # h는 l-velue로 정의되더라도 미리 선언된 내용 때문에 전역 변수
return h
print f(10)
print h # 전역 변수 h 값이 함수 내에서 변경되었음
20 20
g = 10
def f():
a = g # l-value로 사용되는 g는 전역 변수
g = 20 # r-value로 정의되는 g는 지역 변수
return a
print f()
--------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) <ipython-input-68-e323361344da> in <module>() 6 return a 7 ----> 8 print f() <ipython-input-68-e323361344da> in f() 2 3 def f(): ----> 4 a = g # l-value로 사용되는 g는 전역 변수 5 g = 20 # r-value로 정의되는 g는 지역 변수 6 return a UnboundLocalError: local variable 'g' referenced before assignment
g = 10
def f():
global g # g는 전역 변수로 선언됨
a = g # a는 지역 변수, g는 전역 변수
g = 20 # g는 전역 변수
return a
print f()
10
l = []
print dir(l)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
print __builtin__.abs(-5)
print __builtin__.bool(0)
5 False
print dir(__builtins__)
['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']
x = 2
def F():
x = 1
def G():
print x
G()
F()
1
def f(x):
def g(i):
print i,
if i: g(i-1)
g(x)
f(3)
3 2 1 0
def bank_account1(initial_balance):
balance = initial_balance
def deposit(amount):
balance = balance + amount
return balance
def withdraw(amount):
balance = balance - amount
return balance
return deposit, withdraw
d, w = bank_account1(100)
print d(100)
--------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) <ipython-input-78-1f31280de582> in <module>() 10 11 d, w = bank_account1(100) ---> 12 print d(100) <ipython-input-78-1f31280de582> in deposit(amount) 2 balance = initial_balance 3 def deposit(amount): ----> 4 balance = balance + amount 5 return balance 6 def withdraw(amount): UnboundLocalError: local variable 'balance' referenced before assignment
def bank_account2(initial_balance):
balance = [initial_balance]
def deposit(amount):
balance[0] = balance[0] + amount
return balance[0]
def withdraw(amount):
balance[0] = balance[0] - amount
return balance[0]
return deposit, withdraw
d, w = bank_account2(100)
print d(100)
print w(50)
200 150
def incr(a, step=1):
return a + step
b = 1
b = incr(b) # 1 증가
print b
b = incr(b, 10) # 10 증가
print b
2 12
def incr(step=1, a):
return a + step
File "<ipython-input-82-67693752f310>", line 1 def incr(step=1, a): SyntaxError: non-default argument follows default argument
def incr(a, step=1, step2=10):
return a + step + step2
print incr(10)
21
def area(height, width):
return height * width
#순서가 아닌 이름으로 값이 전달
a = area(width=20, height=10)
print a
b = area(height='height string ', width=3)
print b
200 height string height string height string
area(20, width=5)
100
area(width=5, 20)
File "<ipython-input-80-32b5ca4bbf7f>", line 1 area(width=5, 20) SyntaxError: non-keyword arg after keyword arg
def incr(a, step=1, step2=10, step3=100):
return a + step + step2 + step3
print incr(10, 2, step2=100)
212
def incr(a, step=1, step2=10, step3=100):
return a + step + step2 + step3
print incr(10, 2, step2=100, 200)
File "<ipython-input-89-3dbdc3e84e66>", line 4 print incr(10, 2, step2=100, 200) SyntaxError: non-keyword arg after keyword arg
def incr(a, step=1, step2=10, step3=100):
return a + step + step2 + step3
print incr(10, 2, step2=100, step3=200)
312
def varg(a, *arg):
print a, arg
varg(1)
varg(2,3)
varg(2,3,4,5,6)
1 () 2 (3,) 2 (3, 4, 5, 6)
def printf(format, *args):
print format % args
printf("I've spent %d days and %d night to do this", 6, 5)
I've spent 6 days and 5 night to do this
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
def g(a, b, *args, **kw):
print a, b
print args
print kw
g(1,2,3,4, c=5, d=6)
1 2 (3, 4) {'c': 5, 'd': 6}
def g(a, b, **kw, *args):
print a, b
print args
print kw
g(1,2,3,4, c=5, d=6)
File "<ipython-input-96-347cf21aa6c9>", line 1 def g(a, b, **kw, *args): ^ SyntaxError: invalid syntax
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
lambda: 1
<function __main__.<lambda>>
f = lambda: 1
f()
1
g = lambda x, y: x + y
print g(1, 2)
3
incr = lambda x, inc = 1: x + inc
print incr(10) #inc 기본 인수 값으로 1 사용
print incr(10, 5)
11 15
vargs = lambda x, *args: args
print vargs(1,2,3,4,5)
(2, 3, 4, 5)
kwords = lambda x, *args, **kw: kw
kwords(1,2,3,a=4,b=6)
{'a': 4, 'b': 6}
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]
#더하기, 빼기, 곱하기, 나누기에 해당하는 람다 함수 리스트 정의
func = [lambda x, y: x + y, lambda x, y: x - y, lambda x, y: x * y, lambda x, y: x / y]
#메뉴를 표시하고 메뉴를 입력받는다(0-4).
def menu():
print "0. add"
print "1. sub"
print "2. mul"
print "3. div"
print "4. quit"
return input('Select menu:')
#메뉴를 표시하고 선택된 메뉴를 실행한다.
while 1:
sel = menu() # 메뉴 표시하고 키 입력 받음
if sel < 0 or sel > len(func): # 범위를 벗어나면 다시 메뉴 표시
continue
if sel == len(func): # quit이면 종료
break
x = input('First operand:') # 첫번째 인수
y = input('Second operand:') # 두번째 인수
print 'Result =', func[sel](x,y) # 해당함수 호출
0. add 1. sub 2. mul 3. div 4. quit
def f(x):
return x * x
X = [1, 2, 3, 4, 5]
Y = map(f, X)
print Y
[1, 4, 9, 16, 25]
def f(x):
return x * x
X = [1, 2, 3, 4, 5]
Y = []
for x in X:
y = f(x)
Y.append(y)
print Y
[1, 4, 9, 16, 25]
X = [1, 2, 3, 4, 5]
print map(lambda x: x * x, X)
[1, 4, 9, 16, 25]
Y = map(lambda x: x * x + 4 * x + 5, range(10))
print Y
[5, 10, 17, 26, 37, 50, 65, 82, 101, 122]
y = map(lambda x: len(x), ["Hello", "Python", "Programming"])
print y
[5, 6, 11]
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']
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', 'c', 'd']
b = (1, 2, 3, 4)
c = [5, 6, 7, 8]
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print map(None, a, b, c, d)
[('a', 1, 5, 'a'), ('b', 2, 6, 'c'), ('c', 3, 7, 'b'), ('d', 4, 8, 'd')]
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)]
print zip([1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12])
[(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]
a = [[1, 2, 3], [4, 5, 6]]
print zip(*a)
print
b = [(1, 2, 3), (4, 5, 6)]
print zip(*b)
print
c = ([1, 2, 3], (4, 5, 6))
print zip(*c)
print
[(1, 4), (2, 5), (3, 6)] [(1, 4), (2, 5), (3, 6)] [(1, 4), (2, 5), (3, 6)] [(1, 4), (2, 5), (3, 6)]
filter(lambda x: x > 2, [1, 2, 3, 34])
[3, 34]
y = []
for x in [1, 2, 3, 34]:
if x > 2:
y.append(x)
print y
[3, 34]
filter(lambda x: x % 2, [1, 2, 3, 4, 5, 6])
[1, 3, 5]
filter(lambda x: x % 2 - 1, [1, 2, 3, 4, 5, 6])
[2, 4, 6]
def F():
x = 1
print filter(lambda a: a > x, range(-5, 5))
F()
[2, 3, 4]
print filter(lambda x: x > 2, [1, 2, 3, 34])
print filter(lambda x: x > 2, (1, 2, 3, 34))
print filter(lambda x: x < 'a', 'abcABCdefDEF')
[3, 34] (3, 34) ABCDEF
L = ['high', False, 'level', '', 'built-in', '', 'function', 0, 10]
L = filter(None, L)
print L
['high', 'level', 'built-in', 'function', 10]
print reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
15
단계 | x | y | reduce |
---|---|---|---|
1 | 0 | 1 | 1 |
2 | 1 | 2 | 3 |
3 | 3 | 3 | 6 |
4 | 6 | 4 | 10 |
5 | 10 | 5 | 15 |
print reduce(lambda x, y: x + y, [1, 2, 3, 4, 5], 100)
115
print reduce(lambda x, y: x + y * y, range(1, 11), 0)
385
x = 0
for y in range(1, 11):
x = x + y * y
print x
385
print reduce(lambda x, y: y + x, 'abcde')
edcba
단계 | x | y | reduce |
---|---|---|---|
1 | 0 | 'a' | 'a' |
2 | 'a' | 'b' | 'ba' |
3 | 'ba' | 'c' | 'cba' |
4 | 'cba' | 'd' | 'dcba' |
5 | 'dcba' | 'e' | 'edcba' |
def f(a, b, c=1):
'func attribute testing'
localx = 1
localy = 2
return 1
print f.__doc__ # 문서 문자열
print f.func_doc
print f.__name__ # 함수의 이름
print f.func_name
print
print f.func_defaults # 기본 인수값들
func attribute testing func attribute testing f f (1,)
print f.func_code # 함수의 코드 객체
<code object f at 0x10b3c8730, file "<ipython-input-2-de3c51ae9202>", line 1>
def f(a, b, c, *args, **kw): # 함수 정의
localx = 1
localy = 2
return 1
code = f.func_code # 코드 객체 참조
print code.co_name # 함수의 이름
print code.co_argcount # 필수적인 인수의 개수
print code.co_nlocals # 지역변수의 개수
print code.co_varnames # 지역변수의 이름들
f 3 7 ('a', 'b', 'c', 'args', 'kw', 'localx', 'localy')
def sum(N):
if N == 1: # 종결 조건
return 1 # 종결 조건이 만족할 때의 반환 값
return N + sum(N-1) # 재귀 호출
print sum(10)
55