In [1]:
def plus_ten(x):
    return x + 10;

In [2]:
list(map(plus_ten, [1,2,3]))


Out[2]:
[11, 12, 13]

In [3]:
list(map(str,[1,2,3]))


Out[3]:
['1', '2', '3']

In [4]:
str([1,2,3])


Out[4]:
'[1, 2, 3]'

In [5]:
list(map(int,['1','10','100']))


Out[5]:
[1, 10, 100]

In [7]:
list(map(lambda x: x + 10, [1,2,3]))


Out[7]:
[11, 12, 13]

In [8]:
f = lambda x: x + 10

In [9]:
list(map(f,[2,3,4]))


Out[9]:
[12, 13, 14]

In [11]:
(lambda : 1)()  #매개 변수가 없는 람다


Out[11]:
1

In [12]:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [14]:
list(map(lambda x: str(x) if x % 3 == 0 else x , a)) #람다는 일단 리턴 부터 써주고 나서 조건을 사용 한다.


Out[14]:
[1, 2, '3', 4, 5, '6', 7, 8, '9', 10]

In [16]:
list(map(lambda x:str(x) if x%3==0 else x,a))


Out[16]:
[1, 2, '3', 4, 5, '6', 7, 8, '9', 10]

In [17]:
list(map(lambda x: str(x) if x<3 else x if x<6 else x+10,a))


Out[17]:
['1', '2', 3, 4, 5, 16, 17, 18, 19, 20]

In [18]:
a = [1,2,3,4,5]
b = [6,7,8,9,10]

In [19]:
list(map(lambda x,y: x*y ,a,b))  #두개의 리스트를 받아 하나로 만든다.


Out[19]:
[6, 14, 24, 36, 50]

In [20]:
a = [1,2,3,4,5,6,7,8,9,10]

In [21]:
list(filter(lambda x : x % 3 == 0,a))


Out[21]:
[3, 6, 9]

In [22]:
from functools import reduce  #파이썬3 부터 표준 라이브러리에서 제외되었다.

In [23]:
reduce(lambda x,y: x+y,a)


Out[23]:
55

In [24]:
a


Out[24]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [25]:
[ i for i in a if i % 3 == 0 ]


Out[25]:
[3, 6, 9]

In [26]:
a


Out[26]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [28]:
x = 0
for i in a:
    x = x + int(i)
print(x)


55

In [29]:
li = [1,2,3]

In [30]:
type(li)


Out[30]:
list

In [31]:
di = {}

In [32]:
type(di)


Out[32]:
dict

In [33]:
se = set()

In [34]:
type(se)


Out[34]:
set

In [35]:
type('a')


Out[35]:
str

In [36]:
type(3)


Out[36]:
int

In [37]:
type(3.0)


Out[37]:
float

In [38]:
type(lambda x: x)


Out[38]:
function

In [39]:
class Test:
    def to_string(self):
        print("hello")

In [43]:
type(Test)


Out[43]:
type

In [44]:
test = Test()

In [45]:
test.to_string()


hello

In [46]:
type(test)


Out[46]:
__main__.Test

In [47]:
type(test.to_string)


Out[47]:
method

In [1]:
import math

In [2]:
math


Out[2]:
<module 'math' from '/Users/jaegyuhan/anaconda3/lib/python3.5/lib-dynload/math.so'>

In [3]:
math.sin(0.7)


Out[3]:
0.644217687237691

In [4]:
math.sin(1)


Out[4]:
0.8414709848078965

In [5]:
math.sin(0)


Out[5]:
0.0

In [6]:
math.sin(131234)


Out[6]:
-0.24748301545153414

In [7]:
math.log10(10)


Out[7]:
1.0

In [8]:
math.log(4)


Out[8]:
1.3862943611198906

In [9]:
math.log2(4)


Out[9]:
2.0

In [10]:
math.log2(8)


Out[10]:
3.0

In [11]:
math.log2(255)


Out[11]:
7.994353436858858

In [12]:
math.log2(9)


Out[12]:
3.169925001442312

In [13]:
def add_p_tag(str):
    return "<p>{}</p>".format(str)

In [14]:
add_p_tag("hello")


Out[14]:
'<p>hello</p>'

In [15]:
# https://practicaltypography.com/straight-and-curly-quotes.html

In [17]:
print(eval("123 4 5 6".replace(" ","+")))


138

In [22]:
int(sum([1,2,3]) / 3)


Out[22]:
2

In [23]:
isinstance(42, int)


Out[23]:
True

In [24]:
isinstance(42, float)


Out[24]:
False

In [25]:
isinstance(42.0, int)


Out[25]:
False

In [26]:
isinstance(42.0, float)


Out[26]:
True

In [27]:
42.0 == 42


Out[27]:
True

In [28]:
42.0


Out[28]:
42.0

In [29]:
c = "hello"

In [30]:
l = list(c)

In [31]:
l


Out[31]:
['h', 'e', 'l', 'l', 'o']

In [32]:
isinstance(c,list)


Out[32]:
False

In [33]:
isinstance(l,list)


Out[33]:
True

In [34]:
l == list


Out[34]:
False

In [35]:
list1 = [1, 2, 3]
list2 = [1, 2, 3]

if list1 is list1:  #is 연산을 하면 같은 인스턴스인지를 검사한다.
    print("당연히 list1과 list1은 같은 인스턴스입니다.")

if list1 == list2:  #== 연산을 하면 같은 값을 가지고 있는지를 검사한다.
    print("list1과 list2의 값은 같습니다.")
    if list1 is list2:
        print("그리고 list1과 list2는 같은 인스턴스입니다.")
    else:
        print("하지만 list1과 list2는 다른 인스턴스입니다.")


당연히 list1과 list1은 같은 인스턴스입니다.
list1과 list2의 값은 같습니다.
하지만 list1과 list2는 다른 인스턴스입니다.

In [36]:
isinstance(1,int)


Out[36]:
True

In [37]:
ii = int()

In [38]:
ii


Out[38]:
0

In [39]:
ii = float()

In [40]:
ii


Out[40]:
0.0

In [41]:
ii.hex()


Out[41]:
'0x0.0p+0'

In [42]:
class Human():
    """인간"""

In [43]:
person1 = Human()
person2 = Human()

In [44]:
person1.language = "한국어"

In [45]:
person2.language = "English"

In [46]:
person1.name = "서울시민"

In [47]:
person2.name = "인도인"

In [48]:
def speak(person):
    print("{}{}로 말을 합니다.".format(person.name, person.language))

In [49]:
Human.speak = speak

In [50]:
person1.speak()


서울시민이 한국어로 말을 합니다.

In [51]:
person2.speak()


인도인이 English로 말을 합니다.

In [65]:
class Human:
    def __init__(self, name):
        self.name = name
    
    def __str__(self):
        """문자열화 함수"""
        return "이름은 {}".format(self.name)

In [66]:
h = Human('alice')

In [67]:
print(h)


이름은 alice

In [68]:
class A():
    def a(self):
        pass

In [69]:
a = A()

In [70]:
print(a)


<__main__.A object at 0x104251a58>

In [72]:
type(None)


Out[72]:
NoneType

In [77]:
type(1)


Out[77]:
int
연습문제 3-1

In [86]:
def right_justify(str):
    print("{:>70}".format(str))
    print("-" * 70 , str)
    print("                                                                      ",str)

In [87]:
right_justify('monty')


                                                                 monty
---------------------------------------------------------------------- monty
                                                                       monty
연습문제3-2

In [88]:
def do_twice(f):
    f()
    f()

In [89]:
def print_spam():
    print('spam')

In [90]:
do_twice(print_spam)


spam
spam

In [91]:
def do_twice(f,v):
    f(v)
    f(v)

In [92]:
def print_spam(v):
    print(v)

In [93]:
do_twice(print_spam, 'ham')


ham
ham

In [94]:
def print_twice(bruce):
    print(bruce)
    print(bruce)

In [95]:
do_twice(print_twice, 'spam')


spam
spam
spam
spam

In [96]:
def do_four(f,v):
    do_twice(f,v)
    do_twice(f,v)

In [97]:
do_four(print_spam, 'banana')


banana
banana
banana
banana
연습문제3-3

In [99]:
def draw():
    print("+----+----+")
    print("|    |    |")
    print("|    |    |")
    print("|    |    |")
    print("|    |    |")
    print("+----+----+")
    print("|    |    |")
    print("|    |    |")
    print("|    |    |")
    print("|    |    |")
    print("+----+----+")

In [100]:
draw()


+----+----+
|    |    |
|    |    |
|    |    |
|    |    |
+----+----+
|    |    |
|    |    |
|    |    |
|    |    |
+----+----+

In [1]:
def foo():
    global x
    x = 20
    print(x)

In [2]:
foo()


20

In [3]:
x


Out[3]:
20

In [8]:
locals()  #전역 네임스페이스의 요소들을 확인 한다.


Out[8]:
{'In': ['',
  'def foo():\n    global x\n    x = 20\n    print(x)',
  'foo()',
  'x',
  'locals()',
  'for i, key in enumerate(locals()):\n    print(locals()[key])',
  'for i in list(locals()):\n    print(locals()[i])',
  'def print_hello():\n    hello = "hello world"\n    def print_message():\n        print(hello)',
  'locals()'],
 'Out': {3: 20, 4: {...}},
 '_': {...},
 '_3': 20,
 '_4': {...},
 '__': 20,
 '___': '',
 '__builtin__': <module 'builtins' (built-in)>,
 '__builtins__': <module 'builtins' (built-in)>,
 '__doc__': 'Automatically created module for IPython interactive environment',
 '__loader__': None,
 '__name__': '__main__',
 '__package__': None,
 '__spec__': None,
 '_dh': ['/Users/jaegyuhan/PythonEx_1/토요_파이썬'],
 '_i': 'def print_hello():\n    hello = "hello world"\n    def print_message():\n        print(hello)',
 '_i1': 'def foo():\n    global x\n    x = 20\n    print(x)',
 '_i2': 'foo()',
 '_i3': 'x',
 '_i4': 'locals()',
 '_i5': 'for i, key in enumerate(locals()):\n    print(locals()[key])',
 '_i6': 'for i in list(locals()):\n    print(locals()[i])',
 '_i7': 'def print_hello():\n    hello = "hello world"\n    def print_message():\n        print(hello)',
 '_i8': 'locals()',
 '_ih': ['',
  'def foo():\n    global x\n    x = 20\n    print(x)',
  'foo()',
  'x',
  'locals()',
  'for i, key in enumerate(locals()):\n    print(locals()[key])',
  'for i in list(locals()):\n    print(locals()[i])',
  'def print_hello():\n    hello = "hello world"\n    def print_message():\n        print(hello)',
  'locals()'],
 '_ii': 'for i in list(locals()):\n    print(locals()[i])',
 '_iii': 'for i, key in enumerate(locals()):\n    print(locals()[key])',
 '_oh': {3: 20, 4: {...}},
 '_sh': <module 'IPython.core.shadowns' from '/Users/jaegyuhan/anaconda3/lib/python3.5/site-packages/IPython/core/shadowns.py'>,
 'exit': <IPython.core.autocall.ZMQExitAutocall at 0x104075f60>,
 'foo': <function __main__.foo>,
 'get_ipython': <bound method InteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 0x103e7d668>>,
 'i': '_',
 'key': 'quit',
 'print_hello': <function __main__.print_hello>,
 'quit': <IPython.core.autocall.ZMQExitAutocall at 0x104075f60>,
 'x': 20}

In [10]:
def print_hello():
    hello = "hello world"
    def print_message():
        print(hello)
    print_message()

In [11]:
print_hello()


hello world

In [14]:
def calc():
    total = 0
    def add(a,b):
        nonlocal total  #바깥 함수의 지역변수 total을 사용하겠다고 설정
        total = total + a + b
    
    add(2,3)
    add(4,5)
    print(total)

In [15]:
calc()


14

In [19]:
aaa = 0
def aaaa():
    nonlocal aaa #에러 발생 함
    aaa = aaa + 1
    print(aaa)
aaaa()
print(aaa)


  File "<ipython-input-19-aa55c4f0567f>", line 3
    nonlocal aaa
SyntaxError: no binding for nonlocal 'aaa' found

In [20]:
def A():
    x = 10
    y = 100
    def B():
        x = 20
        def C():
            nonlocal x
            nonlocal y
            x = x + 30
            y = y + 300
            print(x)
            print(y)
        C()
    B()
A()


50
400

In [21]:
x = 1
def A():
    x = 10
    y = 100
    def B():
        x = 20
        def C():
            global x
            nonlocal y
            x = x + 30
            y = y + 300
            print(x)
            print(y)
        C()
    B()
A()


31
400

In [22]:
def calc():
    a = 3
    b = 5
    def mul_add(x):  #클로저 함수 이다.
        return a * x + b
    return mul_add

In [25]:
c = calc() # 여기서 calc함수는 종료가 된다. 
print(c(1), c(2))  #이 사용되는 시점이 클로저이다. calc에 선언된 지역변수들이 계속 유지 되어 진다.


8 11

In [29]:
list(map(c, range(1,10)))


Out[29]:
[8, 11, 14, 17, 20, 23, 26, 29, 32]

In [33]:
from functools import reduce

In [36]:
reduce(lambda x,y: x + y, list(map(c, range(1, 10))))


Out[36]:
180

In [37]:
def calc():
    a = 3
    b = 5
    return lambda x: a * x + b

In [38]:
c = calc()

In [39]:
print(list(map(c, range(1,10))))


[8, 11, 14, 17, 20, 23, 26, 29, 32]

In [40]:
def calc():
    a = 3
    b = 5
    total = 0
    def mul_add(x):  #클로저 함수 이다.
        nonlocal total
        total = total + a * x + b
        print(total)

    return mul_add

In [41]:
c = calc()

In [42]:
c(1)


8

In [43]:
c(2)


19

In [44]:
c(3)


33

In [45]:
def counter():
    i = 0
    def add():
        nonlocal i
        i += 1
        return i
    return add

In [50]:
#서로 독립적으로 돌아간다.
c1 = counter()
c2 = counter()

In [51]:
print(c1())
print(c2())
print(c2())


1
1
2

In [52]:
print(c1())


2

In [53]:
print(c2())


3

In [58]:
def call_name(str):
    print("hello " + str)

In [59]:
call_name("강용호")


hello 강용호

In [60]:
def call_name(str):
    return "hello " + str

In [61]:
print(call_name("강용호"))


hello 강용호

In [62]:
def cal_money(money, rate, days):
    return money * rate * (days/365)

In [63]:
import math

In [64]:
def cal_money(rate, year):
    return math.pow((1 + 0.01 * rate), year)

In [65]:
cal_money(10,10)


Out[65]:
2.5937424601000023

In [66]:
math.pow(2,3)


Out[66]:
8.0

In [80]:
def circle_area(r):
    """
    r : 원의 반지름
    원의 넓이를 구합니다.
    """
    return math.sqrt(math.pi * 2)

In [81]:
circle_area(2)


Out[81]:
2.5066282746310002

In [73]:
help(circle_area)


Help on function circle_area in module __main__:

circle_area(r)
    원의 넓이를 구합니다.


In [ ]: