- 비교연산자
4 > 2 # True 크다
5 < 1 # False 작다
6 >= 5 # True 크거나 같다
4 <= 4 # True 작거나 같다
3 == 5 # False 같다
4 != 7 # True 같지 않다
- 논리연산자
a = 4 > 2 # True
not a # False NOT 연산자로 참을 거짓으로, 거짓을 참으로 바꿔준다.
a and b # False AND 연산자로 모두 참이어야 참을 반환한다.
a or b # True OR 연산자로 둘 중 하나만 참이면 참이다.
- 문자열 나누기
# 이메일 주소에서 도메인 'gmail'만 추출하기
myemail = 'test@gmail.com'
result = myemail.split('@') # ['test','gmail.com'] (뒤에 배울 '리스트'라는 자료형이에요 :))
result[0] # test (리스트의 첫번째 요소)
result[1] # gmail.com (리스트의 두 번째 요소
result2 = result[1].split('.') # ['gmail','com']
result2[0] # gmail -> 우리가 알고 싶었던 것
result2[1] # com
# 한 줄로 한 번에!
myemail.split('@')[1].split('.')[0]
- 단어를 쪼개고 싶을땐
- text = sparta
- print(text[:3]) = spa
- .split()
- 이때 특이한건 젤 앞에 나눠진게 1이 아니라 0부터 시작한다는 점
phone = "02-123-1234"
print(phone.split("-")[0])
- list
a = [1, 3, 2, 4]
print(a[3]) # 4
print(a[1:3]) # [3, 2]
print(a[-1]) # 4 (맨 마지막 것)
- 덧붙이기
a = [1, 2, 3]
a.append(5)
print(a) # [1, 2, 3, 5]
a.append([1, 2])
print(a) # [1, 2, 3, 5, [1, 2]]
# 더하기 연산과 비교!
a += [2, 7]
print(a) # [1, 2, 3, 5, [1, 2], 2, 7]
- 정렬하기
a = [2, 5, 3]
a.sort()
print(a) # [2, 3, 5]
a.sort(reverse=True)
print(a) # [5, 3, 2]
- 요소 들어가있는지 확인하기
a = [2, 1, 4, "2", 6]
print(1 in a) # True
print("1" in a) # False
print(0 not in a) # True
- 딕셔너리
- 딕셔너리의 값을 업데이트하거나 새로운 쌍의 자료를 넣을 수 있습니다.
person = {"name":"Bob", "age": 21}
person["name"] = "Robert"
print(person) # {'name': 'Robert', 'age': 21}
person["height"] = 174.8
print(person) # {'name': 'Robert', 'age': 21, 'height': 174.8}
- 딕셔너리의 밸류로는 아무 자료형이나 쓸 수 있고, 다른 딕셔너리를 넣을 수도 있다
person = {"name":"Alice", "age": 16, "scores": {"math": 81, "science": 92, "Korean": 84}}
print(person["scores"]) # {'math': 81, 'science': 92, 'Korean': 84}
print(person["scores"]["science"]) # 92
- 딕셔너리 + 리스트
people = [{'name': 'bob', 'age': 20}, {'name': 'carry', 'age': 38}]
# people[0]['name']의 값은? 'bob'
# people[1]['name']의 값은? 'carry'
person = {'name': 'john', 'age': 7}
people.append(person)
# people의 값은? [{'name':'bob','age':20}, {'name':'carry','age':38}, {'name':'john','age':7}]
# people[2]['name']의 값은? 'john'
- 조건문
# 조건문
money = 5000
if money > 3800:
print("택시 타자!")
-------------------------------------
# 조건을 만족하지 않을 때 다른 코드를 실행하고 싶을 때 쓰는 문법
money = 2000
if money > 3800:
print("택시 타자!")
else:
print("걸어가자...")
-------------------------------------
# 다중조건
age = 27
if age < 20:
print("청소년입니다.")
elif age < 65:
print("성인입니다.")
else:
print("무료로 이용하세요!")
- 짝수 출력하기
num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]
for num in num_list:
if num % 2 == 0:
print(num)
num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]
count = 0
for num in num_list:
if num % 2 == 0:
count += 1
print(count)
- 최댓값 구하기
max = 0
for num in num_list:
if max < num:
max = num
print(max)
- 튜플 : 편집 불가
a = (1,2,3)
print(a[0])
a = (1,2,3)
a[0] = 99 (불가능)
a_dict = [('bob','24'),('john','29'),('smith','30')]
- 집합 (set) : 중복제거
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)
a = ['사과','감','수박','참외','딸기']
b = ['사과','멜론','청포도','토마토','참외']
a_set = set(a)
b_set = set(b)
print(a_set & b_set) # 교집합
print(a_set | b_set) # 합집합
- 문자를 숫자로 바꿀 때는 int
- 숫자를 문자로 바꿀 때는 str
- 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 = str(s['score'])
print(name+'는 '+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:
if person['age'] > 20:
print (person['name'])
--------------------------------------
for person in people:
try:
if person['age'] > 20:
print (person['name'])
except:
name = person['name']
print(f'{name} - 에러입니다')
- 한 줄에 쓰기
# if문 한줄쓰기
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)
- 코드카타
41. 조건에 맞는 도서 리스트 출력하기
BOOK 테이블에서 2021년에 출판된 '인문' 카테고리에 속하는 도서 리스트를 찾아서 도서 ID(BOOK_ID), 출판일 (PUBLISHED_DATE)을 출력하는 SQL문을 작성해주세요.
결과는 출판일을 기준으로 오름차순 정렬해주세요.
SELECT book_id,
date_format(published_date,'%Y-%m-%d') as PUBLISHED_DATE
from book
where category = '인문' and (published_date like '2021%')
order by 2
42. 평균 일일 요금 구하기
CAR_RENTAL_COMPANY_CAR 테이블에서 자동차 종류가 'SUV'인 자동차들의 평균 일일 대여 요금을 출력하는 SQL문을 작성해주세요. 이때 평균 일일 대여 요금은 소수 첫 번째 자리에서 반올림하고, 컬럼명은 AVERAGE_FEE 로 지정해주세요.
- 내 풀이
- 소수 반올림 모름.. → round(반올림할 컬럼, 소수점 반올림 위치)
SELECT avg(daily_fee) as AVERAGE_FEE
from car_rental_company_car
where car_type = 'SUV'
- 정답
SELECT round(avg(daily_fee)) as AVERAGE_FEE
from car_rental_company_car
where car_type='SUV'
43. 조건에 맞는 사용자와 총 거래금액 조회하기
USED_GOODS_BOARD와 USED_GOODS_USER 테이블에서 완료된 중고 거래의 총금액이 70만 원 이상인 사람의 회원 ID, 닉네임, 총거래금액을 조회하는 SQL문을 작성해주세요. 결과는 총거래금액을 기준으로 오름차순 정렬해주세요.
- 내 풀이
- 거래 완료만 빼야햇음
- 총금액임
SELECT u.user_id,
u.nickname,
sum(b.price) as total_sales
from used_goods_board as b join used_goods_user as u on b.writer_id = u.user_id
where b.price>700000
group by 1
order by 3
- 정답
SELECT u.user_id,
u.nickname,
sum(b.price) as total_sales
from used_goods_board as b join used_goods_user as u on b.writer_id = u.user_id
where b.status='done'
group by 1,2
having sum(b.price)>=700000
order by 3
'파이썬' 카테고리의 다른 글
[250311] 파이썬 종합반 5주차 + 알고리즘 6-10 (0) | 2025.03.11 |
---|---|
[250310] 파이썬 종합 4주차 + 코드카타 64-65 + 알고리즘 1-5 (0) | 2025.03.10 |
[250307] 파이썬 종합반 3주차 + 코드카타 61 - 63 (1) | 2025.03.07 |
[250306] 파이썬 종합 2주차 + 코드카타 51-60 (0) | 2025.03.06 |
[250305] 파이썬 종합 1주차 + 코드카타 44-50 (0) | 2025.03.05 |