맥북 비밀번호 설정
terminal에서 Homebrew 설치하기
Homebrew란?
'다운로드 패키지'를 관리할 수 있는 툴.
brew install 프로그램 이름 입력하면 프로그램 다운로드 해준다.
/bin/bash -c "$(curl -fsSL [https://raw.githubusercontent.com/Homebrew/install/master/install.sh](https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
$ brew -v
로 확인하면 됨.brew tap mongodb/brew
brew install mongodb-community
brew services start mongodb-community
만약 실행 안되면
$ brew update
하고 다시 실행해보자!
👉 http://localhost:27017 에 접속했을 때, 아래와 같은 화면을 만나면 잘 된 것
다운로드: https://robomongo.org/download
Download Robo 3T 다운받기
나홀로 메모장 API (GET)
http://spartacodingclub.shop/post
-> 로딩 후 바로 실행 해야함!
$(document).ready(function(){
listing();
});
function listing() {
console.log('화면 로딩 후 잘 실행되었습니다');
// 이 아래에 Ajax 활용해 카드 붙여주는 코드 넣으면 됨.
}
<script>
$(document).ready(function () {
// 처음 새로고침 됐을때 카드 지워줘야 함
$('#cards-box').empty();
listing();
})
function listing() {
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/post",
data: {},
success: function (response) {
let rows = response['articles'];
for(let i = 0; i < rows.length; i++){
// API에서 원하는 데이터 추출
let comment = rows[i]['comment'];
let desc = rows[i]['desc'];
let image = rows[i]['image'];
let title = rows[i]['title'];
let url = rows[i]['url'];
// 카드 붙이기
let temp_html = ``;
temp_html = `<div class="card">
<img class="card-img-top"
src="${image}"
alt="Card image cap">
<div class="card-body">
<a href="${url}" class="card-title">${title}</a>
<p class="card-text">${desc}</p>
<p class="card-text comment">${comment}</p>
</div>
</div>`;
$('#cards-box').append(temp_html);
}
}
})
}
</script>
print('Hello, sparta')
a = 3 # 3을 a에 넣는다
b = a # a를 b에 넣는다
a = a + 1 # a+1을 다시 a에 넣는다
num1 = a*b # a*b의 값을 num1이라는 변수에 넣는다
num2 = 99 # 99의 값을 num2이라는 변수에 넣는다
숫자 / 문자 / boolean 형
name = 'bob' # 문자열
num = 12 # 숫자
is_number = True # True/False -> "Boolean"형
리스트 형 (Javascript의 배열형과 동일)
a_list = []
a_list.append(1) # 리스트에 값을 넣는다
a_list.append([2,3]) # 리스트에 [2,3]이라는 리스트를 다시 넣는다
# a_list = [1,[2,3]]
# a_list[0] = 1
# a_list[1] = [2,3]
# a_list[1][0] = 2
Dictionary 형 (Javascript의 dictionary형과 동일)
a_dict = {}
a_dict = {'name':'bob','age':21}
a_dict['height'] = 178
# a_dict = {'name':'bob','age':21, 'height':178}
# a_dict['name'] = 'bob'
# a_dict['age'] = 21
# a_dict['height'] = 178
Dictionary 형과 List형의 조합
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'
함수의 정의
# 수학문제에서
f(x) = 2*x+3
y = f(2)
y의 값은? 7
# 참고: 자바스크립트에서는
function f(x) {
return 2*x+3
}
# 파이썬에서
def f(x):
return 2*x+3
y = f(2)
y의 값은? 7
함수의 응용
def sum_all(a,b,c):
return a+b+c
def mul(a,b):
return a*b
result = sum_all(1,2,3) + mul(10,10)
# result = 6 + 100 = 106
if / else 로 구성
# oddeven이라는 이름의 함수를 정의, num을 변수로 받음.
def oddeven(num):
# num을 2로 나눈 나머지가 0이면
if num % 2 == 0:
# True (참)을 반환
return True
# 아니면,
else:
# False (거짓)을 반환
return False
result = oddeven(20)
# result의 값은 무엇일까요? True
def is_adult(age):
# 조건이 참이면 성인입니다를 출력
if age > 20:
print('성인입니다')
# 조건이 거짓이면 청소년이에요를 출력
else:
print('청소년이에요')
is_adult(30)
# 무엇이 출력될까요? -> '성인입니다'
파이썬에서 반복문은, 리스트의 요소들을 하나씩 꺼내쓰는 형태. (무조건 리스트와 함께 쓰임)
fruits = ['사과','배','감','귤']
for fruit in fruits:
print(fruit)
# 사과, 배, 감, 귤 하나씩 꺼내어 찍힘
리스트 예제: 과일 개수 세기 함수
fruits = ['사과','배','배','감','수박','귤','딸기','사과','배','수박']
count = 0
for fruit in fruits:
if fruit == '사과':
count += 1
print(count)
# 사과의 개수를 세어 보여줍니다. -> 2
def count_fruits(target):
count = 0
for fruit in fruits:
if fruit == target:
count += 1
return count
subak_count = count_fruits('수박')
print(subak_count) #수박의 개수
gam_count = count_fruits('감')
print(gam_count) #감의 개수
딕셔너리 예제
people = [{'name': 'bob', 'age': 20},
{'name': 'carry', 'age': 38},
{'name': 'john', 'age': 7},
{'name': 'smith', 'age': 17},
{'name': 'ben', 'age': 27}]
# 모든 사람의 이름, 나이 출력해보기
for person in people:
print(person['name'], person['age'])
# 반복문, 조건문 응용한 함수
# 이름을 받으면, age를 리턴해주는 함수
def get_age(myname):
for person in people:
if person['name'] == myname:
return person['age']
return '해당하는 이름이 없습니다'
print(get_age('bob')) # 20 리턴
print(get_age('kay')) # '해당하는 이름이 없습니다' 리턴
👉 패키지? 라이브러리?
- Python에서 패키지는 모듈(일종의 기능들 묶음)을 모아 놓은 단위이다.
- 이런 패키지 의 묶음을 라이브러리로 볼 수 있음.
- 외부 라이브러리를 사용하기 위해서 패키지를 설치할 예정
즉, 여기서는 패키지 설치 = 외부 라이브러리 설치!
📌 예시 문제상황:
만약 회사에서 패키지 A/B/C 쓰고, 개인프로젝트에서는 패키지 B/C/D/E 설치해서 쓰고 있었다고 가정해보자.
그런데 회사에서 B를 이전 버전인 B'
로 쓰자고 한다면?
-> 같은 컴퓨터에 깔려있는 개인프로젝트 에서는 코드를 B'
버전으로 다 바꿔줘야 한다....
💡 해결책:
다 담아둘 필요 없이 공구함을 2개 만들어서,
공구함1에 A, B', C를 담아두고,
공구함2에 B, C, D, E를 담아두고 쓰면 관리하기 편하지 않을까?
-> 가상환경이라는 개념의 등장.
-> 즉, 프로젝트별 공구함 이라고 생각하면 됨.
👉 가상환경(virtual environment) = venv
같은 시스템에서 실행되는 다른 파이썬 응용 프로그램들의 동작에 영향을 주지 않기 위해, 파이썬 배포 패키지들을 설치하거나 업그레이드하는 것을 가능하게 하는 격리된 실행 환경출처 : 파이썬 공식 용어집- 가상환경
👉 새로운 프로젝트의 라이브러리를 가상환경에 설치하려면 pip를 이용함.
서울시 대기 OpenAPI에서, 중구의 NO2 값 가져오기
import requests # requests 라이브러리 설치 필요
r = requests.get('http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99')
rjson = r.json()
print(rjson['RealtimeCityAir']['row'][0]['NO2'])
모든 구의 IDEX_MVL 값 출력하기
import requests # requests 라이브러리 설치 필요
r = requests.get('http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99')
rjson = r.json()
gus = rjson['RealtimeCityAir']['row']
for gu in gus:
print(gu['MSRSTE_NM'], gu['IDEX_MVL'])
IDEX_MVL 값이 60 미만인 구만 출력하기
import requests # requests 라이브러리 설치 필요
r = requests.get('http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99')
rjson = r.json()
gus = rjson['RealtimeCityAir']['row']
for gu in gus:
if gu['IDEX_MVL'] < 60:
print (gu['MSRSTE_NM'], gu['IDEX_MVL'])