내일배움캠프 AI - 2일차 TIL, 2022.04.19

Dongwoo Kim·2022년 4월 19일
1

TIL / WIL

목록 보기
2/113

스파르타 코딩클럽

내일배움캠프 AI 웹개발자양성과정 2회차

20220419 2일차- TIL

1. 아직은 어색한 사이

09:00-12:30 오전 공부

캠프 이틀차. 아직 팀원들과는 어색한 기류가 역력하다. 시간지 조금 더 지나면 괜찮아 지겠지.
오늘은 따로 매니저나 튜터님들의 공지 없이 바로 자율학습을 시작했다. 뭔가 아무런 안내없이 알아서 시작하려니 조금 어색했다. 어제는 팀원들과 이야기해야하는 시간도 중간중간 많은데 일일히 그때마다 노트북을 들고 휴게실로 가는 게 너무 불편했다. 그래서 오늘은 스터디카페가 아닌 집에서 공부했다. 그런데 오히려 안 좋은 점도 있었다. 아침부터 방에서 공부하려니 잠이 너무 쏟아졌다. 진짜 피곤이 몰려오는 듯한 느낌.. '아 스터디카페 갈걸 그랬나..' 생각을 진짜 많이 했다. 내일은 어떡하지..

아무튼 공부내용은 캠프에서 제공해준 python 기초문법! 당연히 python은 많이 써봤기 때문에 간단히 듣기만하면 되겠거니.. 생각했다. 그런데 오히려 내가 잘 몰랐던 내용이 많았다.

그리고 웹프로그래밍 기초 강의 2, 3주차를 듣고보니 시간이 엄청 빠르게 지나있었다. 전에 들었던 강의와 거의 비슷하긴 했는데 중간에 mongoDB를 local이 아니라 cloud를 이용하는 것이 달라서 그부분은 더 주의깊게 들었다.

2. 집인데 더 피곤한 것에 대하여

12:30-13:30 점심시간
13:30-14:00 팀 회의

2시부터 게스타에 모인다고 해서 30분 일찍 점심시간을 가졌다. 사실 30분 일찍 쉬지 않으면 진짜 못 견딜 것 같았다. 왜 집에서 공부하는게 더 피곤한지 모르겠다. 아무튼 밥먹고 정신차리고보니 점심시간이 모두 지나있었다. 2시가 되기전에 잠깐 팀원들과 내일 있을 미니프로젝트에 대해서 이야기했다. 다행히도 프로젝트 공지사항에 메뉴얼이 잘 나와있어서 큰 기획은 할 필요가 없었다.

3. 팀별 자기소개 시간

14:00~15:00 팀별 자기소개

게스타(강당)에 모여서 팀별로 자기소개 시간을 가졌다. 당황스러웠던 것은 팀장이 대표로 팀원들을 모두 소개해야했는데 우리팀이 2번째라서 뭣도모르고 나가서 횡설수설한 것 같았다. ㅠ 그래도 팀원들 반응이 괜찮아서 다행이었고 우리팀말고도 다른 팀들도 정말 다양한 사람들이 모여있었다. 유쾌한 팀도 있었고 개성넘치는 팀들, 진짜 조용한 팀 등 진짜 다양했다. 나중에 팀이 로테이션되면 이들 중 또 어떤 사람들과 만나게 될지 궁금하다.

4. 미니 프로젝트 준비

15:00-19:00 오후 공부 시간

강당에서 모임이 끝나고 이전에 얘기하던 미니프로젝트 관련해서 간단한 이야기를 나눴다. 음악이라는 공통 관심사로 팀이 되었던 것을 활용해서 자기가 좋아하는 노래의 youtube 영상을 소개페이지에 넣기로 했다.

간단한 회의 후 프로젝트에 이용할 git 계정을 만들었다. git을 처음 사용하는 팀원들도 있어서 계정을 만들고 사용하는 방법까지 설명하는데 생각보다 시간이 오래 걸렸다. 나도 git을 많이 써본 적은 없었지만 알고있는 선 안에서 최대한 알려주려고 노력했다.

그리고 일단 내가 기본 골격과 임시 페이지들을 만들어서 repository에 올리고 팀원들에게 push와 pull이 잘 되는지 까지 확인했다. 나는 soucetree를 사용하고 있어서 그걸 소개해줬는데 한 팀원은 githup desktop을 이용한다고해서 나도 한번 사용해봤는데 괜찮은 것 같았다.

5. TIL 제출 까먹지 말자!

19:00-20:00 저녁시간
20:00-21:00 일일 회고 및 TIL 작성

사실 어제 첫날이라고 신나게 TIL을 작성해놓고 제출을 안해서 오늘 매니저님이 찾아는 불상사가 있었다.. WIL만 제출하고 TIL은 제출하는 줄 몰랐는데 실수였다. 신기한 것은 나는 몰랐는데 우리 팀원은 모두 알아서 제출했었다. 이런 내가 팀장이런 것이 참 우리팀.. 걱정이다.
아무튼 중간에 게더 서버도 터지고 생각보다 시간이 근방 지나갔다. 공부할 땐 시간이 안가는데 지금처럼 TIL 작성하는 시간은 왜이렇게 빨리 지나가는 줄 모르겠다. 그래도 오늘 하루도 수고많았고 이런 하루하루가 쌓여서 4개월동안 좋은 결실을 맺을 수 있길 바라고있다. 내일부턴 본격적으로 팀 프로젝트가 시작이니 기대가 된다. 화이팅하자.

6. 개발일지

  1. 튜플과 집합같은 경우에는 거의 사용한 적이 없었기 때문에 '아 이런것도 있었지'라는 생각이 들었다. 사실 튜플은 거의 쓸 일이 없어서 잘 모르겠는데 집합은 알아두면 앞으로도 유용하게 써먹을 곳이 많을 것 같다.
  • 튜플 : 값이 변하지 않는 자료형
    # doc
    people = [{'name':'dongwoo', 'age':29}]
    # tuple
    people = [('dongwoo', 29)]
  • 집합 : 중복 제거
    temp = ['a', 'b', 'c', 'a']
    temp_set = set(temp)
    print(temp_2) # {'a', 'b', 'c'}
    
    # 교집합, 합집합
    a = ['a', 'b', 'c', 'd', 'f']
    b = ['b', 'c', 'd', 'f', 'e']
    
    a_set = set(a)
    b_set = set(b)
    
    print(a_set & b_set)  # {'c', 'b', 'd', 'f'}
    print(a_set | b_set)  # {'c', 'd', 'e', 'f', 'b', 'a'}
    
    # 차집합
    student_a = ['물리2','국어','수학1','음악','화학1','화학2','체육']
    student_b = ['물리1','수학1','미술','화학2','체육']
    
    a_set = set(student_a)
    b_set = set(student_b)
    
    print(a_set - b_set)  # {'음악', '화학1', '국어', '물리2'}
  1. format형태는 많이 써봤는데 python 문법을 공부하면서 f-string을 따로 배운 기억은 없는 것 같다. 그나마 예외처리와 파일불러오기는 코딩하면서 많이 써봤기 때문에 기본지식으로 알고 있었다.
  • f-string
    scores = [
        {'name':'영수','score':70},
        {'name':'영희','score':65},
        {'name':'기찬','score':75},
        {'name':'희수','score':23},
        {'name':'서경','score':99},
        {'name':'미주','score':100},
        {'name':'병태','score':32}
    ]
    
    for s in scores:
        name = s['name']
        score = s['score']
        print(name+'의 점수는 '+str(score))
        print(f'{name}의 점수는 {score}')
  • 예외처리
    people = [
        {'name': 'bob', 'age': 20},
        {'name': 'carry', 'age': 38},
        {'name': 'john', 'age': 7},
        {'name': 'smith', 'age': 17},
        {'name': 'ben', 'age': 27},
        {'name': 'bobby'},
        {'name': 'red', 'age': 32},
        {'name': 'queen', 'age': 25}
    ]
    
    for person in people:
        try:
            if person['age'] > 20:
                print(person['name'])
        except:
            print(person['name'], 'error')
  • 파일 불러오기 main_test.py
    from main_func import *
    
    say_hi()
    say_hi_to('dongwoo')
    main_fun.py
    def say_hi():
        print('hi')
    
    def say_hi_to(name):
        print(f'{name} hi!')
  1. 이번강의에서 가장 쓸만한 내용이 있다면 이부분인 듯 하다. if문과 for문을 한줄로 쓰는 코드들을 볼 때마다 아 이런거지 이해는 하고 있었는데 확실하게 한번 짚고 넘어가니 확 와닿았다. 앞으로 코딩할 때 자주 써먹을 수 있었으면 좋겠다.
  • 한줄로 줄여 쓰기 if 문
    num = 3
    
    if num % 2 == 0:
        result = 'even'
    else:
        result = 'odd'
    
    result = 'even' if num % 2 == 0 else 'odd'
    for 문
    a_list = [1, 3, 2, 5, 1, 2]
    
    b_list = []
    for a in a_list:
        b_list.append(a * 2)
    
    b_list = [a * 2 for a in a_list]
    
    print(b_list) # [2, 6, 4, 10, 2, 4]
  1. lambda는 개인적으로 직관적이지 않은 것 같아서 별로 안 좋아했는데 map, filter와 같이 이용하는 걸 보니 좀 괜찮다고 느껴졌다. map, filter화 한 변수를 list로 다시 감싸줘야하는게 조금 번거롭다고 생각했지만 나름 괜찮은 것 같다.
  • map, lambda, filter
    people = [
        {'name': 'bob', 'age': 20},
        {'name': 'carry', 'age': 38},
        {'name': 'john', 'age': 7},
        {'name': 'smith', 'age': 17},
        {'name': 'ben', 'age': 27},
        {'name': 'bobby', 'age': 57},
        {'name': 'red', 'age': 32},
        {'name': 'queen', 'age': 25}
    ]
    
    result = map(lambda person: 'adult' if person['age'] > 20 else 'teenager', people)
    print(list(result))     
    # ['teenager', 'adult', 'teenager', 'teenager', 'adult', 'adult', 'adult', 'adult']
    
    result = filter(lambda person: person['age'] > 20, people)
    print(list(result))
    # [{'name': 'carry', 'age': 38}, {'name': 'ben', 'age': 27}, {'name': 'bobby', 'age': 57}, {'name': 'red', 'age': 32}, {'name': 'queen', 'age': 25}]
  1. 매개변수와 클래스 문법은 솔직히 내가 사용할 일은 없을 것 같지만 나중에 라이브러리나 함수를 가져와서 사용할 때 필요한 내용인 듯하다.
    특히 함수 매개변수에서 리스트를 개수제한없이 전해줄 수 있는 것은 꽤 유용할 듯 하다.
  • 함수 매개변수
    # 매개변수 무제한으로 받기
    def cal(*args):
        for name in args:
            print(name)
    
    cal(['a', 'b'])         # ['a', 'b']
    cal(['a', 'b', 'c'])    # ['a', 'b', 'c']
    
    # 매개변수를 키워드와 함께 받기
    def cal2(**kwargs):
        print(kwargs)
    
    cal2(name='dongwoo')            # {'name': 'dongwoo'}
    cal2(name='dongwoo', age='29')  # {'name': 'dongwoo', 'age': '29'}
  • 클래스
    class Monster():
        hp = 100
        alive = True
    
        def damage(self, attack):
            self.hp = self.hp - attack
            if self.hp < 0:
                self.alive = False
    
        def status_check(self):
            print('alive') if self.alive else print('dead')
    
    m1 = Monster()
    m1.damage(150)
    m1.status_check()   # dead
    
    m2 = Monster()
    m2.damage(90)
    m2.status_check()   # alive
  1. 웹 프로그래밍 기초 2주차 강의
    이미 알고 있거나 중복된 내용은 빠르게 넘어가고 내가 놓쳤던 내용이나 헷갈릴만한 내용만 기록했다.
  • JQuery 시작하기
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  • ajax
    $.ajax({
        type: "GET",
        url: "http://spartacodingclub.shop/sparta_api/rtan",
        data: {},
        success: function (response) {
            let url = response['url']
            let msg = response['msg']
    
            $('#img-rtan').attr('src', url)
            $('#text-rtan').text(msg)
        }
    })
  • 태그 속성 바꾸기
     // 이미지 url 변경
    $('#img-rtan').attr('src', url)
    
     // text 변경
    $('#text-rtan').text(msg)
  • homework
    <!doctype html>
    <html lang="en">
    
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
              integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
                integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
                crossorigin="anonymous"></script>
    
        <link href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&display=swap" rel="stylesheet">
        <title>스파르타코딩클럽 | 부트스트랩 연습하기</title>
    
        <style>
            * {
                font-family: 'Gowun Dodum', sans-serif;
            }
    
            .mytitle {
                width: 100%;
                height: 250px;
    
                background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://i.ytimg.com/vi/ElHf0dJykug/maxresdefault.jpg');
                background-position: center;
                background-size: cover;
    
                color: white;
    
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
            }
    
            .mypost {
                width: 95%;
                max-width: 500px;
                margin: 20px auto 0px auto;
                padding: 20px;
                box-shadow: 0px 0px 3px 0px gray;
            }
    
            .mybtns {
                display: flex;
                flex-direction: row;
                align-items: stretch;
                justify-content: left;
    
                margin-top: 20px;
            }
    
            .mycard{
                margin: 20px auto 10px auto;
            }
    
        </style>
    
        <script>
            $(document).ready(function () {
                $.ajax({
                    type: "GET",
                    url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
                    data: {},
                    success: function (response) {
                        let temp = response['temp']
                        $('#temp').text(temp)
                    }
                })
            });
        </script>
    
    </head>
    
    <body>
        <div class="mytitle">
            <h1>레드벨벳 웬디 팬명록</h1>
            <p>현재 기온 : <span id="temp">00.00</span></p>
        </div>
        <div class="mypost">
            <div class="form-floating mb-3">
                <input type="email" class="form-control" id="floatingInput" placeholder="name@example.com">
                <label for="floatingInput">닉네임</label>
            </div>
            <div class="form-floating">
        <textarea class="form-control" placeholder="Leave a comment here" id="floatingTextarea2"
                  style="height: 100px"></textarea>
                <label for="floatingTextarea2">응원댓글</label>
            </div>
            <div class="mybtns">
                <button type="button" class="btn btn-dark">응원 남기기</button>
            </div>
    
            <div class="card mycard">
                <div class="card-body">
                    <blockquote class="blockquote mb-0">
                        <p>사! 랑! 해! 요! 레! 드! 벨! 벳! </p>
                        <footer class="blockquote-footer">kimphysicsman<cite title="Source Title"></cite>
                        </footer>
                    </blockquote>
                </div>
            </div>
    
        </div>
    
    </body>
    
    </html>
  1. 웹 프로그래밍 기초 3주차
    javascript에서 repeat 문법은 처음봐서 신기했다.
    나중에 0,1 비트를 나열할 필요가 있을 때 써먹을 수 있을지 않을까 싶다.
  • javascipt 문자열 반복
    let star = 3
    let star_score = '*'.repeat(star)
    
    // star_score == '***'
  • homework
    import requests
    from bs4 import BeautifulSoup
    
    headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
    data = requests.get('https://www.genie.co.kr/chart/top200?ditc=M&rtm=N&ymd=20210701',headers=headers)
    
    soup = BeautifulSoup(data.text, 'html.parser')
    
    #body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.number
    trs = soup.select('#body-content > div.newest-list > div > table > tbody > tr')
    
    for tr in trs:
        rank = tr.select('td.number')
        rank = rank[0].text.split('\n')[0]
        title = tr.select('td.info > a.title.ellipsis')
        title = title[0].text.strip()
        title = title.split('\n')[-1].strip()
        artist = tr.select('td.info > a.artist.ellipsis')
        artist = artist[0].text
        print(rank, title, artist)
  1. 미니프로젝트 골격 만들기
    강의에서 배운 것처럼 flask를 이용했고 아주 간단하게 만들었다.

    • app.py
    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    # HTML 화면 보여주기
    @app.route('/')
    def home():
        return render_template('index.html')
    
    @app.route('/dongwoo')
    def dongwoo_page():
        return render_template('dongwoo.html')
    
    @app.route('/heejeong')
    def heejeong_page():
        return render_template('heejeong.html')
    
    @app.route('/jinyoung')
    def jinyung_page():
        return render_template('jinyoung.html')
    
    @app.route('/songhee')
    def songhee_page():
        return render_template('songhee.html')
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=5000, debug=True)
    
  • index.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
            integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    
        <!-- Optional JavaScript -->
        <!-- jQuery first, then Popper.js, then Bootstrap JS -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
                integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
                crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
                integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
                crossorigin="anonymous"></script>
    
        <!--    google font-->
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Dongle&display=swap" rel="stylesheet">
    
        <title>꾸러기 9조대</title>
    
        <style>
            * {
                font-family: 'Dongle', sans-serif;
            }
    
            .mytitle {
                width: 100%;
                height: 250px;
    
                background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://i.ytimg.com/vi/ElHf0dJykug/maxresdefault.jpg');
                background-position: center;
                background-size: cover;
    
                color: white;
    
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
            }
    
            .youtube{
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
    
                margin: 50px auto 50px auto;
            }
    
            .intro{
                width: 560px;
                margin: 50px auto 50px auto;
            }
    
            .card-box {
                margin: 50px auto 100px auto;
                width: 1000px
            }
    
        </style>
    
        <script>
    
            $(document).ready(function () {
    
            })
    
        </script>
    </head>
    <body>
        <div class="mytitle">
            <h1>꾸러기 9조대</h1>
        </div>
    <div id="youtube" class="youtube">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/gFb1TftvdoM" title="YouTube video player"
                frameborder="0"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                allowfullscreen></iframe>
    </div>
    
        <div class="intro">
            팀 소개 부분
        </div>
    
    <div class="card-deck card-box">
        <div class="card">
            <img class="card-img-top" src="https://avatars.githubusercontent.com/u/103986068?s=400&u=f38774e17d7484d4ea93c0844471f1db51c62b3d&v=4" alt="Card image cap">
            <div class="card-body">
                <h5 class="card-title">김동우</h5>
                <a class="card-text" href="/dongwoo">팀원 소개 바로 가기</a>
            </div>
            <div class="card-footer">
                <small class="text-muted">안녕하세요~</small>
            </div>
        </div>
        <div class="card">
            <img class="card-img-top" src="https://avatars.githubusercontent.com/u/103986068?s=400&u=f38774e17d7484d4ea93c0844471f1db51c62b3d&v=4" alt="Card image cap">
            <div class="card-body">
                <h5 class="card-title">김희정</h5>
                <a class="card-text" href="/heejeong">팀원 소개 바로 가기</a>
            </div>
            <div class="card-footer">
                <small class="text-muted">kimphysicsman</small>
            </div>
        </div>
        <div class="card">
            <img class="card-img-top" src="https://avatars.githubusercontent.com/u/103986068?s=400&u=f38774e17d7484d4ea93c0844471f1db51c62b3d&v=4" alt="Card image cap">
            <div class="card-body">
                <h5 class="card-title">전진영</h5>
                <a class="card-text" href="/jinyoung">팀원 소개 바로 가기</a>
            </div>
            <div class="card-footer">
                <small class="text-muted">kimphysicsman</small>
            </div>
        </div>
        <div class="card">
            <img class="card-img-top" src="https://avatars.githubusercontent.com/u/103986068?s=400&u=f38774e17d7484d4ea93c0844471f1db51c62b3d&v=4" alt="Card image cap">
            <div class="card-body">
                <h5 class="card-title">원송희</h5>
                <a class="card-text" href="/songhee">팀원 소개 바로 가기</a>
            </div>
            <div class="card-footer">
                <small class="text-muted">kimphysicsman</small>
            </div>
        </div>
    </div>
    
    </body>
    </html>
profile
kimphysicsman

1개의 댓글

comment-user-thumbnail
2022년 4월 25일

꾸준하게 작성 잘 해봅시다!

답글 달기