학습목표¶

  • 분기문, 반복문
  • 함수
  • 연산자 etc....
"""제어구문""" if (논리값, 표현식) : 실행코드 조건이 true일때 return 결과 반환 (리턴은 생략이 가능) else : 실행코드 조건이 false 일때

if~elif~else 다중if형태 if (논리값, 표현식) : 실행코드 """ elif (논리값, 표현식) : 실행코드 else : 실행코드

중첩형태 if (논리값, 표현식) : if (논리값, 표현식) : 실행문 else : 실행문 elif (논리값, 표현식) : 실행코드 else : 실행코드

  • 분기문
In [7]:
if True :
    print('good')
else :
    print('bad')
good
  • input() : 콘솔을 통해서 사용자의 입력값을 전달받는 함수
In [11]:
score = input('점수를 입력하세요 : ')
print('type - ', type(score)) # 숫자를 입력했지만 str로 받아짐

score = int(input('점수를 입력하세요 : ')) # 형변환을 통해 int로 만들어주기
print('type - ', type(score))
type -  <class 'str'>
type -  <class 'int'>
In [14]:
score = int(input('점수를 입력하세요 : ')) 
print('type - ', type(score))
if score >= 90:
    if score >= 95:
        print('A+')
    else:
        print('A-')
    
elif score >= 80 :
    print('B')
elif score >= 70 :
    print('C')
elif score >= 60 :
    print('D')
else:
    print('F')
type -  <class 'int'>
A+
In [18]:
print('if ~ in')
areas = ['서울','경기','인천','부산']
region = input('지역을 입력하세요 : ')

if region in areas :
    print('응')
else :
    print(f'{region} 지역은 대상이 아닙니다.')
if ~ in
응
In [23]:
dictTmp = {'melon' : 100, 'bravo' : 200, 'bibibig' : 300}
print('키 존재 유무를 판단하고 싶다면 - ')
target = 'banana'
print('논리값 - ', target in dictTmp)
if target in dictTmp:
    print(dictTmp[target])
else :
    print(f'{target} 키는 대상이 아닙니다')
키 존재 유무를 판단하고 싶다면 - 
논리값 -  False
banana 키는 대상이 아닙니다
In [37]:
# Quiz
# 연산자 : % (나머지), == (동등비교), and (논리곱), or(논리합)
# 윤년 : 4의 배수이고 100의 배수가 아니거나 400의 배수일 때
# 요구사항) input 함수를 이용해서 년도를 입력받아 윤년인지 평년인지를 판단하고 싶다면?

year = int(input('년도를 입력하세요 : '))

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    print(f'{year} 윤년입니다')
else :
    print(f'{year} 평년입니다')
 
2000 윤년입니다
In [46]:
# Quiz
# input 함수를 이용해서 년도, 월을 입력받아서 월의 마지막 날을 출력한다면?

year = int(input('년도를 입력하세요 : '))
month = int(input('월를 입력하세요 : '))

dayLst = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    dayLst[1] = 29
print(f"{year}년 {month}월의 마지막 날은 {dayLst[month -1]}일 입니다")
2025년 10월의 마지막 날은 31일 입니다
  • 날짜타입
  • date , datetime
  • import module
  • from module import function
  • from package.module import function, class
  • form package import module
In [53]:
from datetime import date

today = date.today()
print('type - ', type(today))
print()
print('dir - ', dir(today))
print()
print(today)
print(today.year, today.month, today.day, sep="-")
type -  <class 'datetime.date'>

dir -  ['__add__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__replace__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'ctime', 'day', 'fromisocalendar', 'fromisoformat', 'fromordinal', 'fromtimestamp', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'min', 'month', 'replace', 'resolution', 'strftime', 'timetuple', 'today', 'toordinal', 'weekday', 'year']

2025-10-29
2025-10-29
In [55]:
from datetime import datetime

today = datetime.today()
print('type - ', type(today))
print()
print('dir - ', dir(today))
print()
print(today)
print(today.year, today.month, today.day, sep="-")
type -  <class 'datetime.datetime'>

dir -  ['__add__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__replace__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'astimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fold', 'fromisocalendar', 'fromisoformat', 'fromordinal', 'fromtimestamp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'microsecond', 'min', 'minute', 'month', 'now', 'replace', 'resolution', 'second', 'strftime', 'strptime', 'time', 'timestamp', 'timetuple', 'timetz', 'today', 'toordinal', 'tzinfo', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday', 'year']

2025-10-29 11:05:17.842037
2025-10-29
In [67]:
print('날짜에 대한 연산을 도와주는 모듈 dateutil')
from dateutil.relativedelta import relativedelta
from datetime import timedelta, date

today = date.today()
print('today - ', today)
print('하루 더 한다면?')

# -- 날짜 연산은 + 사용불가
# date 타입과 int타입으로 연산이 불가하기 떄문
# print(today + 1)

# timedelta에는 days만 있고 months나 year가 없다
day = timedelta(days = 1)
print('day - ', day)
print(today + day)

# relativedelta에는 months와 year가 있다
day = relativedelta(days = 1)
month = relativedelta(months = 1)
year = relativedelta(years = 1)

print(year , month , day)

today = today + year
today = today + month
today = today + day
print(today)
날짜에 대한 연산을 도와주는 모듈 dateutil
today -  2025-10-29
하루 더 한다면?
day -  1 day, 0:00:00
2025-10-30
relativedelta(years=+1) relativedelta(months=+1) relativedelta(days=+1)
2026-11-30
In [71]:
print('문자(날짜) -> 날짜')

strDate = '2025-10-29'
print()
today = datetime.strptime(strDate, '%Y-%m-%d')
print(today, type(today))

print()
print('날짜 -> 문자')
today = today.strftime('%Y-%m-%d')
print(today, type(today))
문자(날짜) -> 날짜

2025-10-29 00:00:00 <class 'datetime.datetime'>

날짜 -> 문자
2025-10-29 <class 'str'>
In [77]:
while 조건식 :
    실행문
    초기값에 증감
  Cell In[77], line 3
    초기값에 증감
         ^
SyntaxError: invalid syntax
In [80]:
startDay = datetime.strptime('2025-10-01', '%Y-%m-%d')
endDay = datetime.strptime('2025-10-10', '%Y-%m-%d')

# Quiz
# 날짜 리스트 생성
lst = []

currentDay = startDay
while currentDay <=endDay :
    lst.append(currentDay.strftime('%Y-%m-%d'))
    currentDay += timedelta(days=1)
print(lst)
['2025-10-01', '2025-10-02', '2025-10-03', '2025-10-04', '2025-10-05', '2025-10-06', '2025-10-07', '2025-10-08', '2025-10-09', '2025-10-10']
  • 3항 연산자
  • 결과 if 조건 else 결과
In [82]:
a = 10
b = 20

maxValue = a if a > b else b
print(maxValue)

age = 20
status = "성인" if age >= 19 else "미성년자"
print(status)
20
성인
In [87]:
# Quiz
# 리스트에서 삼항 연산자
# 짝수/홀수 표시한다면?
import random
lst = []
for idx in range(10) :
    nan = random.randint(1,100)
    lst.append(nan)    
print(lst)

result = ["짝수" if data %2 == 0 else "홀수" for data in lst]
print(result)
[44, 17, 27, 80, 65, 23, 34, 99, 85, 40]
['짝수', '홀수', '홀수', '짝수', '홀수', '홀수', '짝수', '홀수', '홀수', '짝수']
In [102]:
# Quiz
# input 함수를 이용해서 핸드폰 번호를 입력 011-xxxx-xxxx , 016-xxxx-xxxx, 019-xxxx-xxxx
# 삼항연산자를 이용해서 통신사의 정보를 확인하고 싶다면

num = input("핸드폰 번호를 입력해 주세요 : ")

result = (
    "SK" if num.split('-')[0] == "011" else
    "LG" if num.split('-')[0] == "016" else
    "KT" if num.split('-')[0] == "019" else
    "error"
)

print("통신사 :", result)
통신사 : SK
In [116]:
# Quiz
# 주민등록번호의 뒷자리 7자리 중 두번째와 세번째는 지역코드
# 지역코드 출생지
# 00 ~ 08 seoul
# 09 ~ 12 busan
# input 함수를 이용해서 주민번호를 입력 xxxxxx-x05xxxx 출생지가 서울인지 아닌지를 판단하고 싶다면?
num = input("주민번호를 입력해 주세요 : ")
print('case01 - ')
region = int(num.split('-')[1][1:3]) 
result = ( "서울 출생" if 0 <= region <= 8 else "기타지역" )
print(result)

print('case02 - ')
seoulCity = ["00","01","02","03","04","05","06","07","08",]
if num.split('-')[1][1:3] in seoulCity:
    print('서울')
else :
    print('서울 외')

print('case03 - ')
print('서울' if num.split('-')[1][1:3] in seoulCity else '서울 외')
case01 - 
서울 출생
case02 - 
서울
case03 - 
서울
In [118]:
# Quiz
# input 함수를 이용해서 시간을 입력받는다
# 입력된 시간이 정각인지 아닌지를 판단하고 싶다면?
# 입력예시) 12:00, 03:10

time = input("시간을 입력해 주세요 : ")
print("정각" if time.split(':')[1] == "00" else "정각아님")
정각
  • 연산자 (산술 > 관계 > 논리)
In [121]:
print(3+4 > 7+3)
print(5 + 10 > 3 and 7+3 == 10)

print((3+4) > (7+3))
print(((5 + 10) > 3) and ((7+3) == 10))
False
True
False
True
"""반복구문""" for ~ in 열거형(range, list, dict, tuple): for ~ else

초기식 while 조건식 : 실행문 초기식 증가

break , continue

In [122]:
for data in range(10):
    print(data)
0
1
2
3
4
5
6
7
8
9
In [133]:
msg = 'see u next time'
for char in msg:
    print(char, end=' ')
print()
for idx in range(len(msg)):
    print(msg[idx], end=' ')
print()
tupleTmp = (4, 6, 1, 3)
for idx, data in enumerate(tupleTmp):
    print('idx - ', idx , 'data - ', data)
s e e   u   n e x t   t i m e 
s e e   u   n e x t   t i m e 
idx -  0 data -  4
idx -  1 data -  6
idx -  2 data -  1
idx -  3 data -  3
In [134]:
wordLst = ['dog', 'dog', 'cat', 'cat', 'word', 'dog', 'cat', 'cs', 'cat', 'cs', 'sk', 'sk'] 
result = {}
for data in wordLst :
    if data in result:
        result[data] += 1
    else :
        result[data] = 1

print(result)
{'dog': 3, 'cat': 4, 'word': 1, 'cs': 2, 'sk': 2}
In [136]:
print('guess game - ')
print('1 ~ 100 사이의 난수를 생성하고 숫자를 맞춰보는 게임')

from random import randint
answer = randint(1, 100)
print('answer - ', answer)
guess game - 
1 ~ 100 사이의 난수를 생성하고 숫자를 맞춰보는 게임
answer -  80
In [148]:
# Quiz
# input 함수를 이용해서 1 ~ 100 사이의 값을 입력받아
# 정답보다 크면 down, 정답보다 작으면 up
# 횟수 10 번으로
# 최종적인 출력예시) 정답 {}, 횟수 {}

from random import randint
answer = randint(1, 100)

for time in range(10):
    a = int(input('숫자를 입력해 주세요 : '))
    if a > answer:
        print('down')
        print(f'남은 횟수 : {9-time}')
    elif a < answer:
        print('up')
        print(f'남은 횟수 : {9-time}')
    else:
        break
print(f'정답 {answer} , 횟수 {time+1}')
up
남은 횟수 : 9
up
남은 횟수 : 8
up
남은 횟수 : 7
down
남은 횟수 : 6
up
남은 횟수 : 5
up
남은 횟수 : 4
정답 84 , 횟수 7
In [160]:
# Quiz
# input 함수를 이용해서 1 ~ 100 사이의 값을 입력받아
# 정답보다 크면 down, 정답보다 작으면 up
# 횟수 10 번으로
# 최종적인 출력예시) 정답 {}, 횟수 {}

from random import randint
answer = randint(1, 100)
print('answer - ', answer)
tries = 1
for idx in range(10):
    guess = int(input('1 ~ 100 사이의 숫자를 입력하세요 : '))
    if answer == guess :
        print('정답')
        break
    elif answer > guess :
        print('up')
    else :
        print('down')
    tries += 1

if answer == guess :
    print(f'정답 {answer} , 시도 횟수 {tries}')
else :
    print(f'정답 {answer} , 제공되는 기회를 전부 사용하였습니다.')
answer -  89
up
up
정답
정답 89 , 시도 횟수 3
In [167]:
# while로 변경해보기

from random import randint
answer = randint(1, 100)
print('answer - ', answer)
tries = 1

while tries <= 10:
    guess = int(input('1 ~ 100 사이의 숫자를 입력하세요 : '))
    if answer == guess :
        print('정답')
        break
    elif answer > guess :
        print('up')
    else :
        print('down')
    tries += 1

if answer == guess :
    print(f'정답 {answer} , 시도 횟수 {tries}')
else :
    print(f'정답 {answer} , 제공되는 기회를 전부 사용하였습니다.')
answer -  7
up
up
up
up
up
up
up
up
up
up
정답 7 , 제공되는 기회를 전부 사용하였습니다.
In [169]:
# Quiz
# input 함수를 이용해서 1 ~ 100 사이의 값을 입력받아
# 정답보다 크면 down, 정답보다 작으면 up
# 횟수 10 번으로
# 최종적인 출력예시) 정답 {}, 횟수 {}

from random import randint
answer = randint(1, 100)
print('answer - ', answer)
tries = 1
for idx in range(10):
    guess = int(input('1 ~ 100 사이의 숫자를 입력하세요 : '))
    if answer == guess :
        print(f'정답 {answer} , 시도 횟수 {tries}')
        break
    elif answer > guess :
        print('up')
    else :
        print('down')
    tries += 1

else :
    print(f'정답 {answer} , 제공되는 기회를 전부 사용하였습니다.')
answer -  44
up
up
up
up
up
up
up
up
up
up
정답 44 , 제공되는 기회를 전부 사용하였습니다.
In [173]:
# while로 변경해보기

from random import randint
answer = randint(1, 100)
print('answer - ', answer)
tries = 1

while tries <= 10:
    guess = int(input('1 ~ 100 사이의 숫자를 입력하세요 : '))
    if answer == guess :
        print(f'정답 {answer} , 시도 횟수 {tries}')
        break
    elif answer > guess :
        print('up')
    else :
        print('down')
    tries += 1

else :
    print(f'정답 {answer} , 제공되는 기회를 전부 사용하였습니다.')
answer -  24
up
up
up
up
up
up
up
up
up
up
정답 24 , 제공되는 기회를 전부 사용하였습니다.
In [188]:
# Quiz 
# 4년에 한번씩 열리는 올림픽이 있다(2024)
# 향후 50년동안 열리는 올림픽의 년도를 출력
# 한 줄에 년도를 5개씩만 출력
# hint) escape sequence : \n, \t


cnt = 0
for year in range(2024, 2074, 4):
    cnt += 1
    if cnt % 5 == 0:
        print(year, end = '\n')
    else :
        print(year, end = '\t')
2024	2028	2032	2036	2040
2044	2048	2052	2056	2060
2064	2068	2072	
In [190]:
dan = int(input("단을 입력하세요 : "))
for gu in range(1, 10):
    print(f'{dan} * {gu} = {dan*gu}')
9 * 1 = 9
9 * 2 = 18
9 * 3 = 27
9 * 4 = 36
9 * 5 = 45
9 * 6 = 54
9 * 7 = 63
9 * 8 = 72
9 * 9 = 81
In [195]:
print('구구단 - ')

for row in range(2, 10) :
    if row == 5 :
        continue
    for col in range(1, 10) : 
        print(f'{row} * {col} = {row*col}', end = "\t")
    print()

    # if row == 3 :
    #     break
구구단 - 
2 * 1 = 2	2 * 2 = 4	2 * 3 = 6	2 * 4 = 8	2 * 5 = 10	2 * 6 = 12	2 * 7 = 14	2 * 8 = 16	2 * 9 = 18	
3 * 1 = 3	3 * 2 = 6	3 * 3 = 9	3 * 4 = 12	3 * 5 = 15	3 * 6 = 18	3 * 7 = 21	3 * 8 = 24	3 * 9 = 27	
4 * 1 = 4	4 * 2 = 8	4 * 3 = 12	4 * 4 = 16	4 * 5 = 20	4 * 6 = 24	4 * 7 = 28	4 * 8 = 32	4 * 9 = 36	
6 * 1 = 6	6 * 2 = 12	6 * 3 = 18	6 * 4 = 24	6 * 5 = 30	6 * 6 = 36	6 * 7 = 42	6 * 8 = 48	6 * 9 = 54	
7 * 1 = 7	7 * 2 = 14	7 * 3 = 21	7 * 4 = 28	7 * 5 = 35	7 * 6 = 42	7 * 7 = 49	7 * 8 = 56	7 * 9 = 63	
8 * 1 = 8	8 * 2 = 16	8 * 3 = 24	8 * 4 = 32	8 * 5 = 40	8 * 6 = 48	8 * 7 = 56	8 * 8 = 64	8 * 9 = 72	
9 * 1 = 9	9 * 2 = 18	9 * 3 = 27	9 * 4 = 36	9 * 5 = 45	9 * 6 = 54	9 * 7 = 63	9 * 8 = 72	9 * 9 = 81	
In [ ]:
 
In [ ]: