본문 바로가기

verdantjuly/Today I Learned

TIL 20230719

728x90

이번 주 목표  Weekly Plan

파이썬 문법 뽀개기

Streamlit을 활용한 웹 서비스 개발

AI가 처음이어도 쉽게 배우는 생성형 AI

웹 개발의 봄 Spring 복습

java 문법 복습

 

오늘 목표  Daily Plan

파이썬 문법 뽀개기

오늘 한 것  Done Today

파이썬 문법 뽀개기

Streamlit을 활용한 웹 서비스 개발

오늘 스케줄  Today's Schedule


6:00 기상, 아침식사, 준비

7:00 Python 강의
12:00 점심식사, 휴식

1:00 Python 강의

8:00 Spring의 봄 강의
12:00 취침

1. 변수 선언과 자료형

사람 : 변수는 값을 담는 상자. (쉽게 생각)

컴퓨터 : 값이 담긴 위치를 가리킨다. 메모리에 올려져 있다. (유식하게 생각)

값에는 여러가지 종류가 들어갈 수 있다. (정수, 실수, 문자열, 참/거짓 형...)

a = 3
b = 2

print(a+b) # 5
print(a ** b) # a의 b제곱
print(a%b) # 나머지

a = (3 > 2) 
print(a) # True

a = (3 == 2)
print(a) # False

 

2. 문자열 다루기

first_name = 'dayoung'
last_name = 'lee'

print(first_name + last_name) # dayounglee

a = 2
b = 'a'
print(b) # a 
# 따옴표 붙으면 무조건 문자열 a

a = '2'
b = 'hello'
print(a + b) # 2hello

a = 2
b = 'hello'
print(a + b) # error : 숫자와 문자를 더할 수 없다

a = str(2) # 문자열 string으로 형변환
b = 'hello'
print(a + b) # 2hello


text = 'abcdefghijk'

result = len(text) # 11
result = text[:3] # abc
result = text[3:] # defghijk

print(result)

myemail = "abc@sparta.co"

result = myemail.split(@)[1].split('.')[0]
print(result) #sparta

 

코딩은 시험이 아님.

대략 범위를 잡고 print.

아닌 것 같으면 고쳐서 돌리기.

 

Quiz. sparta에서 spa만 출력해 보기 

나의 답안

sparta = 'sparta'
print(sparta.split('r')[0])

 

정답

sparta = 'sparta'
print(sparta[:3])

 

나의 생각

r이 나올 때까지 문자열 탐색하는 것보다 앞의 3개만 자르는 게 더 빠를 수도 있다고 생각함

 

Quiz. 전화번호의 지역번호를 출력해 보기

나의 답안

phone = '02-123-1234'
print(phone.split('-')[0])

정답

phone = '02-123-1234'
result = phone.split('-')[0]

print(result)

나의 생각

result라는 변수에 담으면 결과가 뭔지 직관적으로 이해 가능

 

 

3. 리스트와 딕셔너리

list 리스트

리스트에는 숫자 문자 자료형 리스트 전부 담을 수 있다. 

a_list = ['사과', '배', '감']
print(a_list[0]) # 사과

a_list = ['사과', ['배', '감']]
print(a_list[1][1]) # 감

a_list.append(99)
print(a_list[2]) # 99

print(a_list[:1]) # ['사과', ['배', '감']]
print(a_list[-1]) # 맨 마지막 친구가 출력 99
print(len(a_list)) # 3

a_list = [3, 2, 1, 4]
print(a_list.sort()) # 오름차순 정렬 [1,2,3,4]
print(a_list.sort(reverse=True)) # 내림차순 정렬 [4,3,2,1]
print(5 in a_list) # 존재확인 False
print(1 in a_list) # 존재확인 True

 

dictionary 딕셔너리

순서가 없다. 

a_dict = {'name' : "dayoung", 'age' : 29, 'friend':['호상','은한']}
result = a_dict['age'] #29
result = a_dict['friend'][0] #호상

a_dict['height'] = 165 # a_dict에 삽입

print(result)
print('height' in a_dict) # 존재 확인 True

 

리스트 안에 딕셔너리

pepople = [
    {'name' : "dayoung", 'age' : 29},
    {'name' : "john", 'age' : 30}
]

print(pepople[1]['age']) #30

 

Quiz. smith의 science 점수 출력

people = [
    {'name': 'bob', 'age': 20, 'score':{'math':90,'science':70}},
    {'name': 'carry', 'age': 38, 'score':{'math':40,'science':72}},
    {'name': 'smith', 'age': 28, 'score':{'math':80,'science':90}},
    {'name': 'john', 'age': 34, 'score':{'math':75,'science':100}}
]

print(people[2]['score']['science'])

 

4. 조건문

내용물이 되려면 Tab으로 들여쓰기 해서 Depth를 맞춰 줘야 함.

money = 5000

if money > 5000:
    print("택시를 타자")
elif money < 5000:
    print("택시를 못 타")
    print("그럼 뭘 타지?")
else: 
    print("고민해 볼까?")
    
print("밥도 먹어야 해")

 

5. 반복문

fruits = ['사과', '배', '감', '귤']

for fruit in fruits:
    print(fruit)

 

Quiz. 나이가 20보다 큰 사람만 출력합니다.

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}
]

for person in people:
    if person['age']>20:
        print(person)

 

enumerate : 순서(index) 부여하기

break : 멈추기

for i, fruit in enumerate(fruits):
    print(i, fruit)
    if i == 4:
        break

 

Quiz. 리스트에서 짝수만 출력하는 함수 만들기

num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]

def odd_printer(num_list):
    for num in num_list:
        if num % 2 == 0:
            print(num)

odd_printer(num_list)

 

Quiz. 리스트에서 짝수의 개수를 출력하기

num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]

def odd_sum(num_list):
    count = 0
    for num in num_list:
        if num % 2 == 0:
            count = count + 1
    print(count)

odd_sum(num_list)

 

Quiz. 리스트 안에 있는 모든 숫자 더하기

num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]

def add_all(num_list):
    sum = 0
    for num in num_list:
        sum = sum + num
    print(sum)

add_all(num_list)

 

Quiz. 리스트 안에 있는 자연수 중 가장 큰 숫자 구하기

num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]

def biggest_num_printer(num_list):
    num_list.sort(reverse=True)
    print(num_list[0])

biggest_num_printer(num_list)

 

TypeError: 'NoneType' object is not subscriptable sort

sort 함수는 원래 list의 순서를 바꾸고 아무것도 return 하지 않기 때문에 변수에 담길 수 없다. 

 

https://stackoverflow.com/questions/36738141/typeerror-nonetype-object-is-not-subscriptable-scores-sort

6. 함수

def bus_fee(age):
	if age > 65:
	    return 0
	elif age > 20:
	    return 1200
	else:
	    return 0     


money = bus_fee(28)
print(money)

 

Quiz. 주민등록번호를 입력받아 성별을 출력하는 함수 만들기

id = "950717-2034567"

def gender_printer(id):
    if id.split("-")[1][0] == "2" or (id.split("-")[1][0] == "4"):
        print("여자입니다.")
    elif id.split("-")[1][0] == "1" or (id.split("-")[1][0] == "3"):
        print("남자입니다.")
    else:
        print("성별을 판단할 수 없습니다.")


gender_printer(id)

 

7. 튜플, 집합

튜플은 리스트와 비슷하지만 불변인 자료형. 마찬가지로 순서가 존재

a = (1,2,3)

print(a[0]) # 1

 

집합은 중복이 제거된다.

 

a = [1,2,3,4,5,3,4,2,1,2,4,2,3,1,4,1,5,1]

a_set = set(a)

print(a_set)  # {1, 2, 3, 4, 5}

 

a = ['사과','감','수박','참외','딸기']
b = ['사과','멜론','청포도','토마토','참외']

a_set = set(a)
b_set = set(b)

print(a_set - b_set)  # 차집합
print(a_set & b_set)  # 교집합
print(a_set | b_set)  # 합집합

 

8. f-string

for s in scores:
    name = s['name']
    score = str(s['score'])
    print(f'{name}은 {score}점입니다')

 

9. 예외처리

try-except 문

for person in people:
    try:
        if person['age'] > 20:
            print (person['name'])
    except:
        name = person['name']
        print(f'{name} - 에러입니다')

 

10. 파일로 불러오기

main_test.py

from main_func import *

say_hi()

 

main_func.py

def say_hi():
	print('안녕!')

 

11. 한 줄의 마법

삼항연산자

(참일 때 값) if (조건) else (거짓일 때 값)

num = 3

result = "짝수" if num%2 == 0 else "홀수"

print(f"{num}은 {result}입니다.")

 

for문 한방에 써버리기

a_list  = [1, 3, 2, 5, 1, 2]

b_list = [a*2 for a in a_list]

print(b_list)

 

12. map, filter, lambda 식

map 리스트의 모든 원소를 조작하기

def check_adult(person):
    return '성인' if person['age'] > 20 else '청소년'

result = map(check_adult, people)
print(list(result))

 

lambda 함수를 매개변수로 바로 쓰기, 한 줄로 쓰기

result = map(lambda x: ('성인' if x['age'] > 20 else '청소년'), people)
print(list(result))

 

filter 리스트의 모든 원소 중 특별한 것만 뽑기

result = filter(lambda x: x['age'] > 20, people)
print(list(result))

 

13. 함수 심화

 

함수에 인수를 넣을 때, 어떤 매개변수에 어떤 값을 넣을지 정해줄 수 있어요.

def cal(a, b):
    return a + 2 * b

print(cal(3, 5)) # 13
print(cal(5, 3)) # 11
print(cal(a=3, b=5)) # 13
print(cal(b=5, a=3)) # 13

 

특정 매개변수에 디폴트 값을 지정해줄 수 있어요.
def cal2(a, b=3):
    return a + 2 * b

print(cal2(4))
print(cal2(4, 2))
print(cal2(a=6))
print(cal2(a=1, b=7))

 

입력값의 개수를 지정하지 않고 모두 받는 방법

def call_names(*args):
    for name in args:
        print(f'{name}야 밥먹어라~')

call_names('철수','영수','희재')

 

이렇게 여러 개의 인수를 하나의 매개변수로 받을 때 관례적으로 args라는 이름을 사용합니다.

arguments라는 뜻이에요

14. 클래스

아주 많은 것들을 비슷하게 관리해야 할 때 사용

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):
        if self.alive:
            print('살아있다')
        else:
            print('죽었다')

m = Monster()
m.damage(120)

m2 = Monster()
m2.damage(90)

m.status_check()
m2.status_check()

 

 

15.  streamlit 알아보기

  • streamlit 은 홈페이지를 만들어 주는 파이썬의 라이브러리
  • Open AI = Chat GPT를 만든 회사
  • API = Chat GPT를 채팅이 아닌 코드로 보내는 역할

결론 : Chat GPT를 이용해서 웹 서비스 만들어 본다. 

 

파이썬은 라이브러리 환경이 잘 되어 있음

라이브러리 모음 폴더 > venv 가상 환경

 

https://cookbook.openai.com/

에서 뭐든 만들 수 있음.

 

16. 동물 이미지 찾아주기 

 

import streamlit as st

# streamlit document를 활용하여 예제가 아닌 나만의 것으로 만들어 보았다. 

st.title("동물 이미지 찾아 주기 🐯")
st.subheader("영어로 입력해 주세요.",divider="rainbow")
animal = st.chat_input("어떤 동물을 찾아드릴까요?")
if animal:
    with st.chat_message("ai"):
        st.text("잠시만 기다려 주세요.")
        st.image(f"https://edu.spartacodingclub.kr/random/?{animal}")
        st.text(f"예쁜{animal}가 나왔습니다.")

WEB : https://animalfinder.streamlit.app/

Github : https://github.com/verdantjuly/animalfinder

 

17. 제품 홍보 포스터 문구 생성기 

3주차는 도전해 보고 싶어서 혼자 만들어 봤다.

크레딧은 소중하기에 배포는 하지 않았다. 


Github : 
https://github.com/verdantjuly/item_advertiser

 

app.py

import streamlit as st
from ai_image import ai_image 
from ai_text import ai_text

st.title("제품 홍보 포스터 생성기")
st.subheader("당신의 제품을 홍보하고 포스터로 만들어드립니다.",divider="rainbow")
item = st.chat_input("어떤 제품을 홍보해 드릴까요?")
if item:
    with st.spinner("생성 중입니다"):
        image = ai_image(item)
        text = ai_text(item)
        with st.chat_message("ai"):
            st.image(image)
            st.text(text)

 

ai_image.py

import os
from openai import OpenAI

def ai_image(prompt):

  os.environ["OPENAI_API_KEY"] = "API-KEY"

  client = OpenAI(
      api_key=os.environ.get("OPENAI_API_KEY"),
  )

  response = client.images.generate(
    model="dall-e-3",
    prompt=f"{prompt}의 홍보 포스터",
    size="1024x1024",
    quality="standard",
    n=1,
  )

  image_url = response.data[0].url
  return image_url

 

ai_text.py

 

import os
from openai import OpenAI


def ai_text(prompt):
    
    os.environ["OPENAI_API_KEY"] = "API-KEY"

    client = OpenAI(
        api_key=os.environ.get("OPENAI_API_KEY"),
    )

    chat_completion = client.chat.completions.create(
        messages=[
            {
                "role": "user",
                "content": f"{prompt}를 홍보하는 문구를 100자 이내로 적어 줘",
            }
        ],
        model="gpt-4o",
    )

    result = chat_completion.choices[0].message.content

    return result

 

KPT

Keep

뭐든 해 보는 것

Problem

자만하는 것

Try

일단 배워보기

소감  Diary

조금 쉽다는 생각이 들었다. 

그래서 커리큘럼을 다시 읽었다. 

일단 배워보기로 했다. 사전캠프니까...!

 

 

 

 

'verdantjuly > Today I Learned' 카테고리의 다른 글

TIL 20240915  (4) 2024.09.15
TIL 20240724  (0) 2024.07.24
TIL 20240619  (0) 2024.06.19
TIL 20240610  (2) 2024.06.10
TIL 20240606  (0) 2024.06.06