Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

소스코드

실습: 비교연산자를 이용한 if 문

if 3 < 5 :
    print ("3 < 5가 참이면 이 문장이 표시됨")
    
if 3 > 5 :
    print ("3 > 5가 참이면 이 문장이 표시됨")

if 3 <= 5 :
    print ("3 <= 5가 참이면 이 문장이 표시됨")

if 3 >= 5 :
    print ("3 >= 5가 참이면 이 문장이 표시됨")

if 3 == 5 :
    print ("3 == 5가 참이면 이 문장이 표시됨")

if 3 != 5 :
    print ("3 != 5가 참이면 이 문장이 표시됨")    

에어컨 온도조절 동작 코드

temp = 33
user_want_temp = 26

if temp <= user_want_temp :
    print("에어컨을 잠시 멈춥니다.")    

수박이 20,000원 미만이면 한 통 사와

water_melon = 25000

if water_melon < 20000 :
    print("수박을 한 통 구입합니다")

온도가 내려가 에어컨이 멈추면 다시는 에어컨이 재가동되지 않는 문제 해결

temp = 27
user_want_temp = 26

if temp <= user_want_temp :
    print("에어컨을 잠시 멈춥니다.")
else :
    print("에어컨을 가동합니다.")

수박이 20,000원 미만이면 2통 사오고, 그 이상이면 1통만 사와

water_melon = 19000

if water_melon < 20000 :
    print("수박을 2통 구입합니다.")
else :
    print("수박을 1통 구입합니다.")

수박이 20,000원 미만이고 사이다가 1,000원 미만이면 둘 다 하나씩 사와. 그렇지 않으면 아무 것도 사오지 마.

water_melon = 19000
cider = 950

if water_melon < 20000 :
    if cider < 1000 :
        print("수박 1통과 사이다 1개를 구입합니다.")   

수박이 20,000원 미만이고 사이다가 1,000원 미만이면 둘 다 하나씩 사와. 그렇지 않으면 아무 것도 사오지 마.

water_melon = 19000
cider = 1000

if water_melon < 20000 :
    if cider < 1000 :
        print("수박 1통과 사이다 1개를 구입합니다.")
    else:
        print("수박은 싼 데 사이다가 비싸서 아무 것도 안 사감")
else:
    print("일단 수박부터 비싸서 아무 것도 안 사감")    

수박이 20,000원 미만이면 3통 사오고, 20,000원 이상 ~ 25,00미만이면 2통만 사오고, 25,000원 이상이면 1통만 사와

if water_melon < 20000 :
    print("수박을 3통 구입합니다.")
else :
    if water_melon < 25000 :
        print("수박을 2통 구입합니다.")
    else :
        print("수박을 1통 구입합니다.")

수박이 20,000원 미만이면 3통 사오고, 20,000원 이상 ~ 25,00미만이면 2통만 사오고, 25,000원 이상이면 1통만 사와

if water_melon < 20000 :
    print("수박을 3통 구입합니다.")
elif water_melon < 25000 :
    print("수박을 2통 구입합니다.")
else :
    print("수박을 1통 구입합니다.")

실습: 약속에 늦은 날(elif)

message = ""        # 메시지
late = 20           # 지각할 거 같은 시간(분)

if late < 5 :
    message = ""
elif late < 20 :
    message = "미안하다"
else:
    message = "오늘 자동차가 펑크날거 같아"

if message != "":
    print("친구에게 다음과 같이 메시지를 보냈습니다: ", message)

반복문 - while

a = 0

while a < 3 :
    print (a)
    a = a + 1

반복문 - while

a = 0

while True :
    print (a)
    a = a + 1

1, 3, 5, 7, 9, … 와 같이 홀수만 99까지 출력

a = 1

while a <= 99 :
    print(a)
    a = a + 2

반복문 - for

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

for a in data :
    print (a)

1-9까지의 숫자를 list로 만들고 그 목록을 하나씩 출력

nums = [1,2,3,4,5,6,7,8,9]

for a in nums :
    print (a)

좋아하는 음식을 list로 만들고 그 목록을 하나씩 출력

food_list = ["짜장", "회", "탕수육", "트러플버섯", "치킨"]

for food in food_list :
    print (food)

좋아하는 음식을 list로 만들고 그 목록 중 “치킨“이 있을 때만 “치킨 찾았다!” 출력

food_list = ["짜장", "회", "탕수육", "트러플버섯", "치킨"]

for food in food_list :
    if food == "치킨" :
        print (food, "찾았다!")

좋아하는 음식을 list로 만들고 그 목록 중 “탕수육“이 있을 때만 “탕수육 찾았다! O번째에 있었어!” 출력

food_list = ["짜장", "회", "탕수육", "트러플버섯", "치킨"]

index = 0

for food in food_list :
    if food == "탕수육" :
        print (food, "찾았다!", index, "번째에 있었어!")

    index = index + 1

무의미한 반복 작업 중단 - break

food_list = ["짜장", "회", "탕수육", "트러플버섯", "치킨"]

index = 0

for food in food_list :
    if food == "탕수육" :
        print (food, "찾았다!", index, "번째에 있었어!")
	break;

    index = index + 1

break 문이 없을 때

food_list = ["짜장", "회", "탕수육", "트러플버섯", "치킨"]

index = 0

for food in food_list :
    print(index, "번째 자료 조사 중...")
    if food == "탕수육" :
        print (food, "찾았다!", index, "번째에 있었어!")


    index = index + 1

break 문이 있을 때

food_list = ["짜장", "회", "탕수육", "트러플버섯", "치킨"]

index = 0

for food in food_list :
    print(index, "번째 자료 조사 중...")
    if food == "탕수육" :
        print (food, "찾았다!", index, "번째에 있었어!")
        break;

    index = index + 1

목록 중 ‘트러플버섯’ 사달라고 조를 때

food_list = ["짜장", "회", "탕수육", "트러플버섯", "치킨"]

for food in food_list :
    
    if food != "트러플버섯" :
        continue
    print (food, "사 주세요!")

반복문으로 list 값 추가하기(list comprehension)

for i in range(5):
    print(i)

range() 함수 사용해 list 값 추가

a = [i for i in range(10)]

range() 함수 사용해 list 값 추가

a = [i*2 for i in range(10)]

함수 사용하기

def plus1(a) :
    b = a + 1

plus1(10)

함수 결과를 사용하자 - return

def plus1(a) :
    b = a + 1
    return b

c = plus1(10)
print(c)

실습: 두 수를 더해서 return 하는 함수

def plus_2(a, b) :
    return a + b

a = plus_2(10, 20)
print(a)

실습: 두 수를 빼서 return 하는 함수

def minus_2(a, b) :
    return a - b

a = minus_2(10, 20)
print(a)

실습: 두 수 중 더 큰 수를 return 하는 함수

def get_max(a, b):
    if a < b :
        return b
    else :
        return a

res = get_max(10, 11)
print(res)

실습: 두 수 중 더 작은 수를 return 하는 함수

def get_min(a, b):
    if a < b :
        return a
    else :
        return b

res = get_min(10, 11)
print(res)

input() 함수 사용

a = input()
print(a)

화면에 메시지 출력하면서 입력하라고 안내

a = input(“입력하세요:”)
print(a)

input() 함수 사용

a = int( input("1~3중 입력하세요: ") )
print(a)

사용자 키보드로 숫자 값을 받아 1 더한 값을 보여주는 프로그램

a = int( input("숫자를 입력하세요: ") )
b = a + 1
print("결과 :" , b)

사용자 키보드로 숫자 값을 받아 1 뺀 값을 보여주는 프로그램

a = int( input("숫자를 입력하세요: ") )
b = a - 1
print("결과 :" , b)

사용자 키보드로 이름 받아 뒤에 “님 안녕하세요”를 보여주는 프로그램

a = input("이름을 입력하세요: ")
b = a + "님 안녕하세요"
print("결과 : " , b)

파일 새로 만들고 파일에 내용 쓰기

# 파일 생성하고 열기
file = open("sample.txt", 'w')

# 파일에 내용 쓰기
file.write("안녕하세요")

# 파일 닫기. 파일을 열었으면 꼭 닫아야 한다
file.close()

파일 읽기

# 파일 생성하고 열기
file = open("sample.txt", 'r')

# 파일 내용에서 맨 위 한 줄 읽어 오기
line = file.readline()
print (line)

# 파일 닫기. 파일을 열었으면 꼭 닫아야 한다
file.close()

반복문으로 여러 줄 쓰기

file = open("여러줄.txt", 'w')

index = 1

while index <= 100 :
    file.write(str(index))
    file.write("\n")
    index = index + 1

file.close()

여러 줄 읽기

file = open("여러줄.txt", 'r')

while True:
    line = file.readline()
    if not line:
        break;
    print (line)

file.close()

여러 줄 읽기

file = open("여러줄.txt", 'r')

all_line_list = file.readlines()
for line in all_line_list :
    print(line)

file.close()

sample.csv

file = open("sample.csv", 'w')

file.write ("이름,전화번호\n")
file.write ("홍길동,02-1111-1111\n")
file.write ("박길동,02-1111-2222\n")
file.write ("최길동,03-1111-3333\n")

file.close()

HTML 예제

저는 <b>치즈</b>를 좋아하는 <b>MIN</b>입니다.

hypertext

저는 <a>치즈</a>를 좋아하는 <a>MIN</a>입니다.

hypertext

저는 <a href='https://www.lx.or.kr'>치즈</a>를 좋아하는 <a>MIN</a>입니다.

hypertext

저는 <a href='https://www.lx.or.kr' target='_blank'>치즈</a>를 좋아하는 <a>MIN</a>입니다.

HTML5 전반적인 구조

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Insert title here</title>
    </head>
    <body>

    </body>
</html>

list 태그

<ul>
  <li>한식</li>
  <li>
    중식
    <ol>
      <li>짜장면</li>
      <li>짬뽕</li>
    </ol>
  </li>
</ul>

HTML로 표 만들기

<table>
  <tr>
    <td>cell 1</td>
    <td>cell 2</td>
  </tr>    
  <tr>
    <td>cell 3</td>
    <td>cell 4</td>
  </tr>    
</table>

HTML로 표 만들기

<table border=1>
  <tr>
    <td>cell 1</td>
    <td>cell 2</td>
  </tr>    
  <tr>
    <td>cell 3</td>
    <td>cell 4</td>
  </tr>    
</table>

셀 합치기

<table border=1>
  <tr>
    <td colspan=2>cell 1</td>
  </tr>    
  <tr>
    <td>cell 3</td>
    <td>cell 4</td>
  </tr>    
</table>

셀 합치기

<table border=1>
  <tr>
    <td rowspan=2>cell 1</td>
    <td>cell 2</td>
  </tr>    
  <tr>
    <td>cell 4</td>
  </tr>    
</table>

테이블에 헤더 추가

<table border=1>
  <tr>
    <th>cell 1</th>
    <th>cell 2</th>
  </tr>    
  <tr>
    <td>cell 3</td>
    <td>cell 4</td>
  </tr>    
</table>

테이블을 색으로 꾸미기

<table border=1>
  <tr>
    <th>cell 1</th>
    <th>cell 2</th>
  </tr>    
  <tr style="background-color: yellow">
    <td>cell 3</td>
    <td>cell 4</td>
  </tr>    
</table>

테이블을 색으로 꾸미기

<table border=1>
  <tr>
    <th>cell 1</th>
    <th>cell 2</th>
  </tr>    
  <tr>
    <td style="background-color: red">cell 3</td>
    <td>cell 4</td>
  </tr>    
</table>

테이블을 색으로 꾸미기

<table border=1>
  <tr style="background-color: #FF0000">
    <th>cell 1</th>
    <th>cell 2</th>
  </tr>    
  <tr>
    <td>cell 3</td>
    <td>cell 4</td>
  </tr>    
</table>

request를 이용한 통신

import requests
requests.get('https://www.lx.or.kr')

request를 이용한 통신

import requests
requests.get('https://www.lx.or.kr/aaaaa.hwp')

웹서버에서 가져온 html 파일(index.html)

import requests
response = requests.get('https://lxeduweb.web.app')
response

웹서버에서 가져온 html 파일 분석(1.html)

import requests
response = requests.get('https://lxeduweb.web.app/1.html')

웹서버에서 가져온 html 파일 분석(1.html)

import requests
response = requests.get('https://lxeduweb.web.app/1.html')
A = response.text.find('A전자')
start = response.text.find('<td>', A + 3)
end = response.text.find('</td>', start + 1)
price = response.text[start+4 : end]
price

웹서버에서 가져온 html 파일 분석, 정보 표시

import requests
response = requests.get('https://lxeduweb.web.app/1.html')
A = response.text.find('A전자')
start = response.text.find('<td>', A + 3)
end = response.text.find('</td>', start + 1)
price = response.text[start+4 : end]
print("A전자 현재가:", price)

python에서 JSON 사용

import json

data = '{"name": "홍길동", "year": 1999, "phone": "010-1111-1111"}'
value = json.loads(data)

print(value["phone"])

1초에 한 번씩 자동 실행

import schedule
import time

# 실행할 함수 정의
def task():
    print("task 실행")

#1초에 한 번씩 실행
schedule.every(1).seconds.do(task)

while True:
    schedule.run_pending()
    time.sleep(1)

1분에 한 번씩 자동 실행

import schedule
import time

# 실행할 함수 정의
def task():
    print("task 실행")

#1분에 한 번씩 실행
schedule.every(1).minutes.do(task)

while True:
    schedule.run_pending()
    time.sleep(1)

1시간에 한 번씩 자동 실행

import schedule
import time

# 실행할 함수 정의
def task():
    print("task 실행")

# 1시간에 한 번씩 실행
schedule.every(1).hour.do(task)

while True:
    schedule.run_pending()
    time.sleep(1)

매일 00:00에 자동 실행

import schedule
import time

# 실행할 함수 정의
def task():
    print("task 실행")

# 매일 00:00에 실행
schedule.every().day.at("00:00").do(task)

while True:
    schedule.run_pending()
    time.sleep(1)

Openpyxl 기본 사용법(쓰기)

from openpyxl import Workbook
wb = Workbook()

# 워크북(엑셀)에서 활성화된 sheet을 ws라 부름. 
ws = wb.active	

# A1 셀에 자료 할당
ws['A1'] = '공개값'
ws['B2'] = 42   

# 파일 저장
wb.save("sample.xlsx") 

Openpyxl 기본 사용법(셀 읽고 쓰기)

from openpyxl import Workbook
wb = Workbook()

# 워크북(엑셀)에서 활성화된 sheet을 ws라 부름. 
ws = wb.active	

# A1 셀에 자료 할당
ws['A1'] = '공개값'
ws['B2'] = 42   

c = ws['B2'].value
ws['C3'] = c + 1

# 파일 저장
wb.save("sample2.xlsx") 

Openpyxl 기본 사용법(파일 읽기)

from openpyxl import load_workbook
wb = load_workbook(filename = 'sample2.xlsx)

# 워크북(엑셀)에서 활성화된 sheet을 ws라 부름. 
ws = wb['Sheet']	
v = ws['C3'].value
print("v:", v)

python-pptx 기본 사용법

from pptx import Presentation

prs = Presentation() 	# 파워포인트형으로 객체 생성
slide_layout = prs.slide_layouts[1]  		# 레이아웃 설정
slide = prs.slides.add_slide(slide_layout)	# 슬라이드 하나 추가

slide.shapes.title.text = "제목"
slide.shapes.placeholders[1].text_frame.text = '내용1'
slide.shapes.placeholders[1].text_frame.add_paragraph().text = '내용2'

prs.save('sample.pptx')				# 파일 저장