basic_seq_func.py

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def using_range():
    """
    범위 객체
    :return:
    """
 
    # 순차형, 변경 불가
    # len, in, not in
    # 인덱스 접근, 슬라이싱
    r = range(10# 인자값 1개 -> end, 10은 포함되지 않는다
    print(r,type(r))
 
    r = range(01002)
    print(r, "LENGTH:"len(r))
    print(r[19])
    print("포함된 내용",list(r))
 
    # for loop 에서 사용
 
    for num in r:
        print(num, end=" ")
 
 
def using_zip():
    """
    zip 객체
    :return:
    """
    english= "SUN""MON""TUE""WED" # 4개 짜리 튜플
    korean = "일""월""화""수""목""금" # 6개 짜리 튜플
 
    engkor = zip(english, korean)
    print(engkor, type(engkor))
 
 
    # loop
    for item in engkor:
        print(item[0], item[1])
 
    print("=====================")
 
    for eng, kor in engkor:
        print("ENG:", eng, "KOR:", kor)
 
 
 
 
def using_enumerate():
    """
    enumerate 함수
    순차 자료형에서 자료 추출시 인덱스가 함께 필요할 때
    :return:
    """
 
    items = ["Python""Java""Linux""C"]
 
    for item in items:
        print(item, end=" ")
 
    print()
 
    print(enumerate(items))
 
 
 
    # enumerate 를 이용한 loop
    for item in enumerate(items):
        print(item)
 
    for index, value in enumerate(items):
        print("{0}번째 항목={1}".format(index, value))
 
 
if __name__=="__main__":
    #using_range()
    using_zip()
    #using_enumerate()
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

adv_object.py

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# 글로벌 변수
 
g_a = 1
g_b = "Python"
 
 
# 사용자 정의 함수
def func():
    l_a=2
    l_b="Local"
    print("로컬 심볼 테이블 : ", locals())
 
    print("g_a" in locals())
    print(g_a)
 
 
 
def symbol_table():
    print("GLOBAL:", globals())
    print(type(globals()))
 
    print("g_a ?""g_a" in globals())
    print(type(globals()))
 
    func()
 
 
def object_id():
    # Literal 의 id
    a=10
    b=10
    print("ID a:", id(a))
    print("ID b:", id(b))
 
    print("id a == id b ? ", id(a)==id(b))
    print("a is b ?", a is b) # is는 동일성의 비교
 
    #가변형
    lst1=[1,2,3]
    lst2=[1,2,3]
    lst3=lst1
 
    print("LST1:",lst1,type(lst1))
    print("LST2:", lst1, type(lst2))
    print("LST3:", lst1, type(lst3))
 
    print("lst1 == lst2:", lst1 == lst2)
    print("lst1 is lst2:", lst1 is lst2)
    print("lst1 == lst3:", lst1 == lst3)
    print("lst1 is lst3:", lst1 is lst3)
 
 
def object_copy():
    """
    객체의 복사
    :return:
    """
    a = [123]
    b = [456]
    x = [a, b, 100]
 
    print("X:", x)
 
    y = x # 참조 복사 : 심벌 테이블 내 주소값이 동일
    print("Y:",y)
 
    print("x is y ? ", x is y)
    x[2]=10
    print("y[2] ? :", y[2])
 
    # Shallow Copy
    # [:]
    import copy
 
    print("x:",x)
 
    y=copy.copy(x)
 
    print("Y:", y)
    print("x is y ? ", x is y) # 복제되었으므로 다른 객체
 
    x[2]=100
    print("Y:",y)
 
    print("x[0]:", hex(id(x[0])))
    print("y[0]:", hex(id(y[0])))
 
    x[0][0= 2
    print("Y:", y)
 
    # deepcopy : 내부의 모든 객체를 새로 생성
 
    print("x:",x)
    y = copy.deepcopy(x) # 재귀적 카피
 
    print("x[0]:",hex(id(x[0])))
    print("y[0]:", hex(id(y[0])))
 
    x[0][0]=10
    print("Y:", y)
    print("x is y ? ", x is y)
 
 
if __name__=="__main__":
    #func()
    #symbol_table()
    #object_id()
    object_copy()
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

adv_flow_control.py

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
def if_statement():
    """
    if문
    :return:
    """
 
    """
    키보드로부터 money 입력
    10000원 이상 -> by Taxi
    2000원 이상 -> by bus
    아니면 -> on foot
    """
    money=int(input("Money input:"))
    print(money,type(money))
 
    message=""
    if money>10000:
        message="By Taxi"
    elif money>2000:
        message="By bus"
    else:
        message="On foot"
 
    print("가지고 있는 돈 {}, {}".format(money,message))
 
 
def if_expr():
    """
    조건 판별 식(Expression)
    :return:
    """
 
    money = int(input("얼마 가지고 있어?"))
    message="by Taxi" if money >= 10000 \
        else "by Bus" if money >= 2000 else "on foot"
 
    print("가지고 있는 돈 {money}, {message}".format(money=money,message=message))
 
 
def for_ex():
    """
    for문
    :return:
    """
    # 구구단
    # 삼각형 그리기
 
    # for i in range(2,10):
    #     for j in range(1,10):
    #         print(i, "*", j, "=", i*j)
 
 
    for i in range(0,100,2):
        print(i,end=" ")
    else:
        print("루프 정상 종료")
 
 
    for i in range(0,100,2):
        if i>50:
            break
        print(i, end=" ")
    else :
        print("루프 정상 종료")
 
 
 
    str="*"
    for i in range(1,5):
             print(str*i)
 
 
def while_ex():
    """
    while문으로 구구단, 삼각형, 역삼각형
    :return:
    """
 
    i=2
    j=1
    while(i<10):
        while(j<10):
            print(i, "*", j, "=", i*j,end="\t")
            j=j+1
        j=1
        i=i+1
        print()
 
 
    i=0
    while i < 100:
        print(i, end=" ")
        i+=2
    else:
        print("루프 정상 종료")
 
    # 의도적 무한 루프
    i=0
    while True:
        if i % 2 != 0:
            i += 1
            continue
 
        print(i,end=" ")
        i += 1
        if i > 1000:
            break
 
 
def list_comp():
    """
    리스트 컴프리헨션
    :return:
    """
 
    x = range(1,100)
    # 2*x+1 한 리스트로 생성
    result=[]
    for num in x:
        result.append(2*num+1)
 
 
    print("RESULT:",result)
 
 
    # List Comprehension Syntax
    # [ 표현식 for 항목 in 순차형 객체 ]
 
    result = [2*num+1 for num in x]
    print("COMP RESULT:",result)
 
 
    # 1~99까지의 수 중에서 짝수만
    result = [num for num in range(1,100if num%2==0]
    print("짝수:", result)
 
strings = ["a","as","bat","cat","dove","python"]
 
def set_comp():
    """
    셋 컴프리헨션
    :return:
    """
 
    # Syntax : { 표현식 for in 순차객체 }
    # 중복 없고, 순서 없음
    # strings 안에서 문자열의 길이가 3글자 이하인 셋을 생성
 
    filtered_set = { s for s in strings if len(s) <= 3}
    print(filtered_set, type(filtered_set))
 
def dict_comp():
    """
    딕셔너리 컴프리헨션
    :return:
    """
    # Syntax : { 키표현식:값표현식 for 객체 in 순회가능 객체 }
    lens = {s:len(s) for s in strings}
    print(lens)
 
 
if __name__ == "__main__":
    #if_statement()
    #if_expr()
    #for_ex()
    #while_ex()
    #list_comp()
    #set_comp()
    dict_comp()
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

basic_func.py

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# 주로 함수 인수 다루기를 중심으로
 
def sum(a,b):
    return a+b
 
def multiply(a,b=2): # a * b
    return a*b
 
 
print(multiply(10))
print(multiply(10,4))
 
 
def area(width,height):
    return width * height
 
print("4 * 6의 면적",area(4,6)) # width = 6, height = 4
print("4 * 6의 면적(키워드):",area(height=6,width=4))
 
def get_total(*args):
    print("ARGS:",args)
 
    total=0
    for i in args:
        total+=i
 
    return total
 
def get_total2(*args,**kwd):
 
    option1 = kwd.get("option1",None)
    print("옵션 인자:",option1)
    total = 0
    for i in args:
        if isinstance(i,(int, float)):
            total += i
 
    return total
 
print(get_total(12))
print(get_total(1,2,3))
#print(get_total(1,2,"python",3,4))
print("get_total2: ",get_total2(1,2,"python",3,4,option1=True,option2="옵션"))
 
# 확장 연습
# 안쪽에 리스트나 튜플이 있으면
# 리스트 튜플 내부의 합산 가능한 int, float도 함께 합산
 
 
# 함수도 객체다 (1급 시민)
def plus(a,b):
    return a+b
 
def minus(a,b):
    return a-b
 
def calc(a,b,*func): # 함수를 가변 인자로 받음
    for f in func:
        if callable(f): # 함수 인가?
            print(f(a,b))
 
print("============")
calc(10,20,plus)
 
# Lambda
calc(10,20,lambda a, b : a * b) # 일회성 함수 주입
 
# Lambda 함수를 이용한 리스트 소트 키 변경
strings = "Life is too short, you need python"\
    .upper().replace(",","").split()
print(strings)
strings.sort(key=lambda  s:len(s))
print(strings)
 
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

+ Recent posts