나도코딩 파이썬 무료강의(6시간)을 듣고 정리(복습)

치즈말랑이·2021년 9월 6일
0
post-thumbnail

우선 생활코딩에서 html1과 파이썬 강의를 듣고 기초를 더 쌓고 싶어서 이 강의를 들었다.

파이썬 코딩 무료 강의 (기본편) - 6시간 뒤면 여러분도 개발자가 될 수 있어요 [나도코딩]
에 대한 내용을 정리한 것이다.

이후 삼성 SW Expert Academy 파이썬 기초강의 1,2 수강 후
부스트코스에 있는 CS 강의(하버드대 강의) https://www.boostcourse.org/cs112/joinLectures/41307,
KOOC에 있는 자료구조 및 알고리즘 개론 1,2(카이스트 강의) 수강예정
https://kaist.edwith.org/intro-data-and-algo-2018/joinLectures/14730

많은 개념이 있으므로 필요한 것이 있으면 Ctrl+F로 찾으면 된다.

2-3. boolean 자료형
boolean은 참, 거짓을 의미

print(True)
print(False)
print(not True)
----------------
True
False
False

2-4. 변수

animal = "강아지"
name = "연탄이"
age = 4
hobby = "산책"
is_adult = age >= 3 #boolean으로 처리하기 위해 is_ 붙임

print("우리집" +animal+ "의 이름은" +name+ "에요")
print(name + "는" + str(age) + "살이며, " + hobby + "을 아주 좋아해요")
print(name, "는", age, "살이며, ", hobby, "을 아주 좋아해요") #,로 쓰면 무조건 한 칸씩 띄어쓰기 
print(name + "는 어른일까요? " + str(is_adult))
------------------------------------------------------------------------------
우리집강아지의 이름은연탄이에요
연탄이는4살이며, 산책을 아주 좋아해요
연탄이 는 4 살이며,  산책 을 아주 좋아해요
연탄이는 어른일까요? True

Quiz) 변수를 이용하여 다음 문장을 출력하시오

변수명 : station
변수값 : "사당", "신도림", "인천공항" 순서대로 입력
출력문장 : XX행 열차가 들어오고 있습니다.

station = "사당"
print(station+ "행 열차가 들어오고 있습니다.")
station = "신도림"
print(station+ "행 열차가 들어오고 있습니다.")
station = "인천공항"
print(station+ "행 열차가 들어오고 있습니다.")
-------------------------------------------
사당행 열차가 들어오고 있습니다.
신도림행 열차가 들어오고 있습니다.
인천공항행 열차가 들어오고 있습니다.

3-1.연산자

print(2**3) #2^3 = 8
print(5%3) #나머지 구하기 2
print(10%3) #1
print(5//3) #1 몫 구하기
print(10//3) #3
print(1!=3) #!= 는 같지않다.
print(not(1!=3)) # False
print((3>0) and (3<5)) #True
print((3>0) & (3<5)) #True
print((3>0) or (3>5)) #True
print((3>0) | (3>5)) #True

3-2. 간단한수식

number = 14
print(number)
number = number + 2 #16
print(number)
number += 2 #18 number = nubmer + 2와 똑같은 식
print(number)
number *= 2 #36
print(number)
number /= 2 #18
print(number)
number -= 2 #16
print(number)
number %= 5 #1
print(number)

3-3. 숫자처리함수

print(abs(-5)) #5
print(pow(4,2)) #4^2=16
print(max(5,12)) #12
print(min(5,12)) #5
print(round(3.14)) #3 반올림
print(round(4.99)) #5

from math import * # python이 제공하는 math libary 사용
print(floor(4.99)) #내림, 4
print(ceil(3.14)) #올림, 4
print(sqrt(16)) #제곱근, 4

3-4. 랜덤함수

from random import * # python이 제공하는 random library 사용
print(random()) # 0.0~1.0 미만의 임의의 값 생성
print(random()*10) # 0.0~10.0 미만의 임의의 값 생성
print(int(random()*10)) # 0~10 미만의 임의의 값 생성 int: 정수로 변환
print(int(random()*10)+1) # 1~10 이하의 임의의 값 생성
print(int(random()*45)+1) # 1~45 이하의 임의의 값 생성

print(randrange(1,46)) # 1~46 미만의 임의의 값 생성
print(randint(1,45)) # 1~45 이하의 임의의 값 생성

Quiz) 당신은 최근에 코딩 스터디 모임을 새로 만들었습니다.
월 4회 스터디를 하는데 3번은 온라인으로 하고 1번은 오프라인으로 하기로 했습니다.
아래 조건에 맞는 오프라인 모임 날짜를 정해주는 프로그램을 작성하시오.

조건1 : 랜덤으로 날짜를 뽑아야 함
조건2 : 월별 날짜는 다름을 감안하여 최소 일수인 28 이내로 정함
조건3: 매월 1~3일은 스터디 준비를 해야 하므로 제외

(출력문 예제)
오프라인 스터디 모임 날짜는 매월 x일로 선정되었습니다.

from random import *

date = randint(4,28)
print("오프라인 스터디 모임 날짜는 매월" +str(date)+ "일로 선정되었습니다.")

4-1. 문자열

sentence = "나는 소년입니다."
print(sentence)
sentence = '파이썬은 쉬워요.' # " or ' 아무거나 사용해도 상관 없음
sentence = """
나는 소년이고,
파이썬은 쉬워요
"""  #줄바꿈 기능
print(sentence)
----------------------------------------------------------------
나는 소년입니다.
 # 줄바꿈 기능
나는 소년이고,
파이썬은 쉬워요

4-2. 슬라이싱

jumin = "990120-1234567" # 인덱스 0부터 시작

print("성별 : " + jumin[7])
print("연 : " + jumin[0:2]) # 0번째부터 2번째 직전 값까지 0~1
print("월 : " + jumin[2:4])
print("일 : " + jumin[4:6])

print("생년월일 : " +jumin[:6]) # 처음부터 6 직전까지
print("뒤 7자리 : " + jumin[7:]) # 7부터 끝까지 
print("뒤 7자리 (뒤에부터) : " + jumin[-7:]) # 맨 뒤에서 7번째부터 끝까지

4-3. 문자열 처리함수

python = "Python is Amazing"
print(python.lower()) #소문자로 변환
print(python.upper()) #대문자로 변환
print(python[0].isupper()) #0번째 문자가 대문자이면 True, 아니면 False
print(len(python)) #글자수
print(python.replace("Python", "Java")) #Python 글자를 찾아서 Java

index = python.index("n") #python에서 n이 몇번째 글자인지
print(index)
index = python.index("n", index + 1) # 앞에서 찾은 n보다 하나 뒤에서 -> 2번째 n 위치

print(python.find("n")) #n을 찾아줌
print(python.find("Java")) #Java가 이 변수에 포함되어있지 않으면 -1 출력, 뒤에 print("Hi")가 있으면 정상출력
print(python.index("Java")) #에러 출력, 뒤에 print("Hi")가 있어도 에러 그대로 출력

print(python.count("n")) #n이 몇번 나오는지 출력

4-4. 문자열포맷

print("a"+"b")
print("a","b")
-----------------
ab
a b

# 방법1
print("나는 %d살입니다." % 20) #d: 숫자
print("나는 %s을 좋아해요." % "파이썬") #s: 문자열 string 값, 정수&하나의 문자 전부 출력 가능
print("Apple 은 %c로 시작해요." % "A") #c: character 한글자만 출력
print("나는 %s살입니다." % 20)
print("나는 %s색과 %s색을 좋아해요." % ("파란", "빨간"))

# 방법2
print("나는 {}살입니다." .format(20)) #format 괄호 안에 있는 값을 {}안에 넣어 출력
print("나는 {}색과 {}색을 좋아해요." .format("파란", "빨간"))
print("나는 {0}색과 {1}색을 좋아해요." .format("파란", "빨간"))
print("나는 {1}색과 {0}색을 좋아해요." .format("파란", "빨간")) #빨간색과 파란색

# 방법3
print("나는 {age}살이며, {color}색을 좋아해요." .format(age = 20, color="빨간"))
print("나는 {age}살이며, {color}색을 좋아해요." .format(color="빨간", age = 20))

# 방법4 (v3.6 이상~)
age = 20
color = "빨간"
print(f"나는 {age}살이며, {color}색을 좋아해요.")

4-5. 탈출문자

# \n : 줄바꿈
print("백문이 불여일견 \n백견이 불여일타") 
--------------------------------------
백문이 불여일견
백견이 불여일타

#저는 "나도코딩"입니다.
print("저는 "나도코딩"입니다.") # 에러출력
print('저는 "나도코딩"입니다.')
print("저는 \"나도코딩\"입니다.")

# \\ " 문장 내에서 \
print("C:\\Users\\Nadocoding\\Desktop\\PythonWorkspace>")

# \r : 커서를 맨 앞으로 이동
print("Red Apple\rPine")
-------------------------
PineApple

# \b : 백스페이스 (한 글자 삭제)
print("Redd\bApple")
--------------------
RedApple

# \t : 탭
print("Red\tApple") 
--------------------
Red		Apple				

Quiz. 사이트별로 비밀번호를 만들어 주는 프로그램을 작성하시오

예) http://naver.com
규칙1 : http:// 부분은 제외 => naver.com
규칙2 : 처음 만나는 점(.) 이후 부분은 제외 => naver
규칙3 : 남은 글자 중 처음 세자리 + 글자 갯수 + 글자 내 'e' 갯수 + "!" 로 구성
(nav) (5) (1) (!)
예) 생성된 비밀번호 : nav51!

site = "http://naver.com"

sites = site.replace("http://","")
sites = sites[:sites.index(".")]
password = sites[0:3] + str(len(sites)) + str(sites.count("n")) + "!"
print("{0} 의 비밀번호는 {1} 입니다. " .format(site, password))sites = http://naver.com

5-1. 리스트 []

#지하철 칸별로 10명, 20명, 30명
subway1 = 10
subway2 = 20
subway3 = 30

subway = [10, 20, 30]
print(subway)
----------------------
[10, 20, 30]

subway = ["유재석", "조세호", "박명수"]
print(subway)

# 조세호씨가 몇 번째 칸에 타고 있는가?
print(subway.index("조세호")) # 1

# 하하씨가 다음 정류장에서 다음 칸에 탐
subway.append("하하")
print(subway) # ['유재석', '조세호', '박명수', '하하']

# 정형돈씨를 유재석 / 조세호 사이에 태워봄
subway.insert(1, "정형돈") 
print(subway) # ['유재석', '정형돈', '조세호', '박명수', '하하'] 1번자리였던 조세호를 밀어내고 정형돈이 삽입

# 지하철에 있는 사람을 한 명씩 뒤에서 꺼냄
print(subway.pop())
print(subway)

# 같은 이름의 사람이 몇 명 있는지 확인
subway.append("유재석")
print(subway)
print(subway.count("유재석")) # 2

# 정렬도 가능
num_list = [5,2,4,3,1]
num_list.sort() #sort : 정렬
print(num_list)

# 수너 뒤집기 가능
num_list.reverse()
print(num_list)

# 모두 지우기
num_list.clear()
print(num_list)

# 다양한 자료형 함께 사용
mix_list = ["조세호", 20, True] 
print(mix_list) # ['조세호', 20, True]

mix_list = ["조세호", 20, True] 
num_list = [5,2,4,3,1]
num_list.extend(mix_list)
print(num_list)
---------------------------------
[5, 2, 4, 3, 1, '조세호', 20, True]

5-2. 사전

cabinet = {3:"유재석", 100: "김태호"} #3은 key, 유재석은 value
print(cabinet[3])
print(cabinet[100])

print(cabinet.get(3))
print(cabinet[5]) # 키에 5가 없기 때문에 에러가 나서 print("hi")는 출력이 안됨
print("hi")
print(cabinet.get(5)) # 키에 5가 없으면 None 출력하고 print("hi") 출력
print("hi")
print(cabinet.get(5, "사용 가능")) # 키에 5가 없으면 사용 가능 출력
print("hi")

print(3 in cabinet) # cabinet 안에 3이라는 key가 있는가 -> True
print(5 in cabinet) # False

cabinet = {"A-3":"유재석", "B-100":"김태호"}
print(cabinet["A-3"]) # 유재석
print(cabinet["B-100"]) # 김태호

# 새 손님
print(cabinet)
cabinet["A-3"] = "김종국" # 유재석이 빠지고 김종국으로 변경
cabinet["C-20"] = "조세호" # 값 추가
->
cabinet = {"A-3":"유재석", "B-100": "김태호"}
print(cabinet)
cabinet["A-3"] = "김종국" # 유재석이 빠지고 김종국으로 변경
cabinet["C-20"] = "조세호" # 값 추가
print(cabinet)

# 간 손님
del cabinet["A-3"]
print(cabinet)

# key 들만 출력
print(cabinet.keys()) # dict_keys(['A-3', 'B-100', 'C-20'])

#value 들만 출력
print(cabinet.value()) # dict_values(['김종국', '김태호', '조세호'])

#key, value 쌍으로 출력
print(cabinet.items()) # dict_items([('A-3', '김종국'), ('B-100', '김태호'), ('C-20', '조세호')])

# 목욕탕 폐점
cabinet.clear() #{}
print(cabinet)

5-3. 튜플 # list와는 다르게 내용 변경, 추가를 할 수 없음, 속도가 list보다 빠름
변경되지 않는 목록을 사용할때.

menu = ("돈까스", "치즈까스")
print(menu[0])
print(menu[1])

menu.add("생선까스") # 사용 불가. 

name = "김종국"
age = 20
hobby = "코딩"
print(name, age, hobby)

name, age, hobby = "김종국", 20, "코딩")
print(name, age, hobby)

5-4. 집합

#집합 (set)
# 중복 안됨, 순서 없음

my_set = {1,2,3,3,3}
print(my_set)
---------------------
{1, 2, 3}

java = {"유재석", "김태호", "양세형"}
python = set(["유재석","박명수"])

# 교집합 (java와 python을 모두 할 수 있는 개발자)
print(java & python)
print(java.intersection(python))
---------------------------------
{'유재석'}
{'유재석'}

# 합집합 (java 할 수 있거나 python 할 수 있는 개발자)
print(java | python) #or
print(java.union(python)) #합집합
----------------------------------
{'김태호', '양세형', '박명수', '유재석'}
{'김태호', '양세형', '박명수', '유재석'}

# 차집합 (java 할 수 있지만 python은 할 줄 모르는 개발자)
print(java - python)
print(java.difference(python))
-------------------------------
{'김태호', '양세형'}
{'김태호', '양세형'}

# python 할 줄 아는 사람이 늘어남
python.add("김태호")
print(python)
--------------------
{'김태호', '박명수', '유재석'}

# java를 잊었어요
java.remove("김태호")
print(java)
----------------------
{'양세형', '유재석'}

5-5. 자료구조의 변경

#자료구조의 변경
#커피숍
menu = {"커피", "우유", "주스"}
print(menu, type(menu)) 
------------------------------
{'우유', '주스', '커피'} <class 'set'>

menu = list(menu)
print(menu, type(menu))
------------------------
['우유', '주스', '커피'] <class 'list'>

menu = tuple(menu)
print(menu, type(menu))
------------------------
('우유', '주스', '커피') <class 'tuple'>

menu = set(menu)
print(menu, type(menu))
-------------------------
{'우유', '주스', '커피'} <class 'set'>

6-1. if

weather = input("오늘 날씨는 어때요?")
if weather == "비" or weather == "눈":
	print("우산을 챙기세요")
elif weather == "미세먼지":
	print("마스크를 챙기세요")
else:
	print("준비물 필요 없어요")
    
temp = int(input("기온은 어때요?")) # **왜 int를 꼭 붙여야 하는지, str은 왜 안되는지 모르겠다.**
if 30 <= temp:
	print("너무 더워요. 나가지 마세요")
elif 10 <= temp and temp<30:
	print("괜찮은 날씨에요")
elif 0 <= temp < 10:
	print("외투를 챙기세요")
else:
	print("너무 추워요. 나가지 마세요")

6-2. for (반복문)

print("대기번호 :1")
print("대기번호 :2")
print("대기번호 :3")
print("대기번호 :4")

for waiting_no in [0,1,2,3,4]:
	print("대기번호 : {0}".format(waiting_no))
---------------------------------------------
대기번호 : 0
대기번호 : 1
대기번호 : 2
대기번호 : 3
대기번호 : 4

for waiting_no in range(1,6) # 1, 2, 3, 4, 5
	print("대기번호 : {0}".format(waiting_no))
---------------------------------------------
대기번호 : 1
대기번호 : 2
대기번호 : 3
대기번호 : 4
대기번호 : 5

starbucks = ["아이언맨", "토르", "아이엠 그루트"]
for customer in starbucks:
	print("{0}, 커피가 준비되었습니다.".format(customer))
-------------------------------------------------------
아이언맨, 커피가 준비되었습니다.
토르, 커피가 준비되었습니다.
아이엠 그루트, 커피가 준비되었습니다.

6-3. while

#while
customer = "토르"
index = 5
while index >= 1:
	print("{0}, 커피가 준비 되었습니다. {1} 번 남았어요".format(customer,index))
    index -= 1
    if index == 0:
    	print("커피는 폐기처분 되었습니다.")
        
 customer = "아이언맨"
 while True:
 	print("{0}, 커피가 준비 되었습니다. 호출 {1} 회".format(customer,index))
    index += 1
    
 customer = "토르"
 person = "unknown" #person 값은 상관이 없는건지 헷갈린다. unknown이 아니라 철수 같이 다른 이름을 넣어도 작동하고, 어차피 input을 써서 다른 값을 입력하는거면..
 
 while person != customer: # 이 조건을 만족할 때 까지 문장 반복
 	print("{0}, 커피가 준비 되었습니다.".format(customer)) 
    person = input("이름이 어떻게 되세요?")

6-4. continue, break

absent = [2, 5] # 결석
no_book = [7] # 책을 깜빡했음
for student in range(1, 11): # 1,2,3,4,5,6,7,8,9,10
	if student in absent:
    	continue
    elif student in no_book:
    	print("오늘 수업 여기까지. {0}는 교무실로 따라와.".format(student)) #.format()에 들어간 student가 elif에서 student로 한정이 되어있는건지 의문
        break
    print("{0}, 책을 읽어봐".format(student))

6-5. 한 줄 for

# 출석번호가 1 2 3 4, 앞에 100을 붙이기로 함 -> 101, 102, 103, 104.
students = [1, 2, 3, 4, 5]
print(students)
students = [i+100 for i in students]
print(students)

$ 학생 이름을 길이로 변환
students = ["Iron man", "Thor", "I am groot"]
students = [len(i) for i in students}
print(students)

# 학생 이름을 대문자로 변환
students = ["Iron man", "Thor", "I am groot"]
students = [i.upper() for i in students]
print(students)

6-6. Quiz

당신은 Cocoa 서비스를 이용하는 택시 기사님입니다.
50명의 승객과 매칭 기회가 있을 때, 총 탑승 승객 수를 구하는 프로그램을 작성하십시오.

조건1 : 승객별 운행 소요 시간은 5분 ~ 50분 사이의 난수로 정해집니다.
조건2 : 당신은 소요 시간 5분 ~ 15분 사이의 승객만 매칭해야 합니다.

(출력문 예제)
[O] 1번째 손님 (소요시간 : 15분)
[ ] 2번째 손님 (소요시간 : 50분)
[O] 3번째 손님 (소요시간 : 5분)
...
[ ] 50번째 손님 (소요시간 : 16분)

총 탑승 승객 : 2분

from random import *
cnt = 0 # 총 탑승 승객 수
for i in range(1,51): # 1 ~ 50 이라는 수 (승객)
    time = randrange(5,51) # 5분 ~ 50분 소요 시간
    if 5 <= time <= 15: # 5분 ~ 15분 이내의 손님 (매칭 성공), 탑승 승객 수 증가 처리
        print("[O] {0}번째 손님 (소요시간 : {1}분".format(i,time))
        cnt += 1
    else: # 매칭 실패한 경우
        print("[ ] {0}번째 손님 (소요시간 : {1}분".format(i,time))
print("총 탑승 승객 : {0}분".format(cnt))

벨로그에서 코드를 적고 IDE에 옮겨 테스트 해보니 IndentationError: unindent does not match any outer indentation level가 뜬다. IDE에서 새롭게 적으면 정상작동하고, 들여쓰기도 잘 했는데 원인을 모르겠다.
-> 메모장에 옮겨보니 time = randrange(5,51) 부분의 들여쓰기가 이상하게 되어있었다.

7-1. 함수

def open_account():
	print("새로운 계좌가 생성되었습니다.")
open_account()

7-2. 전달값과 반환값

def deposit(balance, money):
	print("입금이 완료되었습니다. 잔액은 {0} 원입니다.".format(balance + money))
    return balance + money # 뭘 반환한다는 것인지 이해가 안된다.
    
def withdraw(balance, money): #출금
	if balance >= money: # 잔액이 출금보다 많으면
    		print("출금이 완료되었습니다. 잔액은 {0} 원입니다.".format(balance - money)) # print 들여쓰기를 왜이렇게 많이 하지?
	else:
    	print("출금이 완료되지 않았습니다. 잔액은 {0} 원입니다.".format(balance))
        return balance
        
def withdraw_night(balance, money): #저녁에 출금
	commission = 100 # 수수료 100원
    return commission, balance - money - commission
    
balance = 0 # 잔액
balance = deposit(balance, 1000)
balance = withdraw(balance, 2000)
commission, balance = withdraw_night(balance, 500) #commission이 앞에 왜 들어가는지 모르겠다.
print("수수료 {0} 원이며, 잔액은 {1} 원입니다.".format(commission, balance))
        

7-3. 기본값

def profile(name, age, main_lang):
	print("이름 : {0}\t나이 : {1}\t주 사용 언어: {2}" \
    	.format(name, age, main_lang))

profile("유재석", 20, "파이썬")
profile("김태호", 25, "자바")

# 같은 학교 같은 학년 같은 반 같은 수업.

def profile(name, age=17, main_lang="파이썬"):
	print("이름 : {0}\t나이 : {1}\t주 사용 언어: {2}" \
    	.format(name, age, main_lang))
        
profile("유재석", 20, "자바")
profile("김태호")
-------------------------------------------------------
이름 : 유재석   나이 : 20       주 사용 언어: 자바
이름 : 김태호   나이 : 17       주 사용 언어: 파이썬
    

7-4. 키워드값

def profile(name, age, main_lang):
	print(name, age, main_lang)
    
profile(name="유재석", main_lang="파이썬", age=20)
profile(main_lang="자바", age=25, name="김태호") # 순서 다르게 해도 결과는 같음
-------------------------------------------------
유재석 20 파이썬
김태호 25 자바

7-5. 가변인자

def profile(name, age, lang1, lang2, lang3, lang4, lang5): # 항상 name, age, 언어 5개가 있어야 작동함
	print("이름: {0}\t 나이 : {1} \t".format(name,age), end=" ")
    print(lang1, lang2, lang3, lang4, lang5)
    
def profile(name, age, *language):
    print("이름 : {0}\t 나이 : {1}\t".format(name, age), end = " ")
    for lang in language:
        print(lang, end = " ")
    print()
    
 profile("유재석", 20, "Python", "Java", "C", "C++", "C#", "JavaSCript")
 profile("김태호", 25, "Kotlin", "Swift")
 
 ----------------------------------------------------------------------------
이름 : 유재석    나이 : 20       Python Java C C++ C# JavaSCript 
이름 : 김태호    나이 : 25       Kotlin Swift

7-6. 지역변수와 전역변수

gun = 10 # 전역 변수

#def checkpoint(soldiers):
#    gun = gun - soldiers
#    print("[함수 내 남은 총 : {0}".format(gun)) # 우항의 gun이 gun = 10의 정보를 못가져온다.
#    
#def checkpoint(soldiers): # 경계근무
#    global gun # 전역 공간에 있는 gun 사용
#    gun = gun - soldiers
#    print("[함수 내] 남은 총 : {0}".format(gun)) # global 함수 사용으로 gun = 10 정보 사용 가능
#
#def checkpoint_ret(gun, soldiers): # 경계근무
#   gun = gun - soldiers
#    print("[함수 내] 남은 총 : {0}".format(gun))
#    return gun

print("전체 총 : {0}".format(gun))
gun = checkpoint_ret(gun, 2)
print("남은 총 : {0}".format(gun))
---------------------------------------------------
전체 총 : 10
[함수 내] 남은 총 : 8
남은 총 : 8

7-7. Quiz

Quiz) 표준 체중을 구하는 프로그램을 작성하시오

  • 표준 체중 : 각 개인의 키에 적당한 체중

(성별에 따른 공식)
남자 : 키(m) x 키(m) x 22
여자 : 키(m) x 키(m) x 21

조건1 : 표준 체중은 별도의 함수 내에서 계산
함수명 : std_weight
전달값 : 키(height), 성별(gender)
조건2 : 표준 체중은 소수점 둘째자리까지 표시

(출력 예제)
키 175cm 남자의 표준 체중은 67.38kg 입니다.

내코드

def std_weight(height, gender):
    if gender == "남자":
        weight = round(height/100 * height/100 * 22,2)
        print("키 {0}cm 남자의 표준 체중은 {1}kg 입니다.".format(height,weight))
    elif gender == "여자":
        weight = round(height/100 * height/100 * 21,2)
        print("키 {0}cm 여자의 표준 체중은 {1}kg 입니다.".format(height,weight))
    else:
        print("성별을 옳바르게 입력해주세요")

나도코딩 코드

def std_weight(height, gender):
    if gender == "남자":
        return height * height * 22
    else:
        return height * height * 21

height = 175
gender = "남자"
weight = round(std_weight(height / 100, gender), 2)
print("키 {0}cm {1}의 표준 체중은 {2}kg 입니다.".format(height, gender, weight))

8-1. 표준 입출력

print("Python", "Java", sep=",", end="?")
print("무엇이 더 재밌을까요?")
-------------------------------------------
Python,Java?무엇이 더 재밌을까요?
import sys
print("Python", "Java", file=sys.stdout) # 표준 출력
print("Python", "Java", file=sys.stderr) # 표준 에러
시험 성적
scores = {"수학" : 0, "영어":50, "코딩":100}
for subject, score in scores.items(): # subject는 key, score는 value, items는 dictionary
    print(subject, score)
    print(subject.ljust(8), str(score).rjust(4), sep=":") 
# 8칸 확보 후 그 안에서 왼쪽으로 정렬, 4칸 확보 후 그 안에서 오른쪽으로 정렬
은행 대기순번표
001, 002, 003, ...
for num in range(1,21):
    print("대기번호 : " + str(num).zfill(3)) # 왼쪽에 3칸 공간 확보 후 값이 없으면 0으로 채움
---------------------------------------------------------------------------------------
대기번호 : 001
대기번호 : 002
대기번호 : 003
·
·
·
대기번호 : 019
대기번호 : 020
answer = input("아무 값이나 입력하세요 : ")
print(type(answer))
print("입력하신 값은 " + answer + " 입니다.")

8-2. 다양한 출력포맷

# 빈 자리는 빈공간으로 두고, 오른쪽 정렬을 하되, 총 10자리 공간을 확보
print("{0: >10}".format(500))
# 양수일 땐 +로 표시, 음수일 땐 -로 표시
print("{0: >+10}".format(+500))
print("{0: >+10}".format(-500))
# 왼쪽 정렬하고, 빈칸으로 _로 채움
print("{0:_<+10}".format(500))
# 3자리 마다 콤마를 찍어주기
print("{0:,}".format(1000000000000))
# 자리 마다 콤마를 찍어주기, +- 부호도 붙이기
print("{0:+,}".format(+1000000000000))
print("{0:+,}".format(-1000000000000))
# 3자리 마다 콤마를 찍어주기, 부호도 붙이고, 자릿수 확보하기, 빈 자리는 ^로 채우기
print("{0:^<30,}".format(1000000000000))
# 소수점 출력
print("{0:f}".format(5/3))
# 소수점 특정 자리수 까지만 표시 (소수점 셋째 자리에서 반올림)
print("{0:.2f}".format(5/3))

8-3. 파일 입출력

score_file = open("score.txt", "w", encoding="utf8") # w: write(쓰기위한 정보)
print("수학 : 0", file=score_file) # 자동으로 줄바꿈이 됨
print("영어 : 50", file=score_file)
score_file.close() # 다 쓰고 파일 종료

score_file = open("score.txt", "a", encoding="utf8") # a: append (추가)
score_file.write("과학 : 80")
score_file.write("\n코딩 : 100")
score_file.close()

score_file = open("score.txt", "r", encoding="utf8") # r: read
print(score_file.read())
score_file.close()

score_file = open("score.txt", "r", encoding="utf8")
print(score_file.readline(), end="") # 한 줄씩 읽기, 한 줄 읽으면 다음 줄로 커서 이동
print(score_file.readline(), end="")
print(score_file.readline(), end="")
print(score_file.readline(), end="")
score_file.close()

# 몇줄인지 모를 때
score_file = open("score.txt", "r", encoding="utf8")
while True:
    line = score_file.readline()
    if not line:
        break
    print(line, end = "")
score_file.close()

score_file = open("score.txt", "r", encoding="utf8")
lines = score_file.readlines() # 모든 줄을 list 형태로 저장
for line in lines: # list에서 한 줄씩 불러와서 출력
    print(line, end="")

score_file.close()

#score_file = open("score.txt", "r", encoding="utf8")
#lines = score_file.readline()
#for line in lines:
#    print(line, end="")
#
#score_file.close()
이거는 같은 코드인데 전체 줄이 안나오고 맨 위 한줄만 나온다. 뭐가 문제인지 모르겠다.

8-4. pickle

데이터를 파일 형태로 저장

import pickle
profile_file = open("profile.pickle", "wb")
# b : pickle에서는 binary 타입 정의 반드시 해야함, 인코딩 설정 안해도 됨
profile = {"이름" : "박명수", "나이" : 30, "취미" :["축구", "골프", "코딩"]}
print(profile)
pickle.dump(profile,profile_file)
profile_file.close()

profile_file = open("profile.pickle", "rb")
profile = pickle.load(profile_file)
print(profile)
profile_file.close()

8-5. with

import pickle # 마지막에 파일을 자동으로 close 해준다.
with open("profile.pickle", "rb") as profile_file:
    print(pickle.load(profile_file))

with open("study.txt", "w", encoding="utf8") as study_file:
    study_file.write("파이썬을 열심히 공부하고 있어요")

with open("study.txt", "r", encoding="utf8") as study_file:
    print(study_file.read())

8-6. Quiz

당신의 회사에서는 매주 1회 작성해야 하는 보고서가 있습니다.
보고서는 항상 아래와 같은 형태로 출력되어야 합니다.

-- X 주차 주간보고 --
부서 :
이름 :
업무 요약 :

1주차부터 50주차까지의 보고서 파일을 만드는 프로그램을 작성하시오.

조건 : 파일명은 '1주차.txt', '2주차.txt', ... 와 같이 만듭니다.

내 코드

for i in range(1,51):
    report_file = open("{0}주차.txt".format(i), "w", encoding="utf8")
    print(" -- {0} 주차 주간보고 -- ".format(i), file=report_file)
    print(" 부서 : ", file=report_file)
    print(" 이름 : ", file=report_file)
    print(" 업무 요약: ", file=report_file)
report_file.close()

나도코딩 코드

for i in range(1, 51):
    with open(str(i) + "주차.txt", "w", encoding="utf8") as report_file:
        report_file.write(" - {0} 주차 주간보고 -".format(i))
        report_file.write("\n부서 :")
        report_file.write("\n이름 :")
        report_file.write("\n업무 요약 :")

9-1. 클래스
9-2. init

# 마린 : 공격 유닛, 군인. 총을 쏠 수 있음
name = "마린" # 유닛의 이름
hp = 40 # 유닛의 체력
damage = 5 # 유닛의 공격력

print("{} 유닛이 생성되었습니다.".format(name))
print("체력 {0}, 공격력 {1}\n".format(hp, damage))

# 탱크 : 공격 유닛, 탱크. 포를 쏠 수 있는데, 일반 모드 / 시즈 모드.

tank_name = "탱크"
tank_hp = 150
tank_damage = 35

print("{} 유닛이 생성되었습니다.".format(tank_name))
print("체력 {0}, 공격력 {1}\n".format(tank_hp, tank_damage))

tank2_name ="탱크"
tank2_hp = "150"
tank2_damage = 35

print("{} 유닛이 생성되었습니다.".format(tank2_name))
print("체력 {0}, 공격력 {1}".format(tank2_hp, tank2_damage))

def attack(name, location, damage):
    print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]".format( \
        name, location, damage))

attack(name, "1시", damage)
attack(tank_name, "1시", tank_damage)
attack(tank2_name, "1시", tank2_damage)

class Unit:
    def __init__(self, name, hp, damage):
        self.name = name
        self.hp = hp
        self.damage = damage

marine1 = Unit("마린", 40, 5)
marine2 = Unit("마린", 40, 5)
tank = Unit("탱크", 150, 35)

# __init__는 생성자, 마린이나 탱크같은 객체가 만들어질 때 자동으로 호출되는 부분
# 객체: 마린이나 탱크와 같이 클래스로부터 만들어 지는 것들을 객체 라고 표현
# 마린과 탱크는 Unit class의 instance라고 한다.
# 객체가 생성될때는 기본적으로 self를 제외하고 이미 생성된 함수개수와 동일한 값을 제공해야함
# ->이름만 제공하던가 hp만 제공하던가 등등

9-3. 멤버변수

class Unit:
    def __init__(self, name, hp, damage):
        self.name = name
        self.hp = hp
        self.damage = damage
        print("{0} 유닛이 생성 되었습니다.".format(self.name))
        print("체력 {0}, 공격력 {1}".format(self.hp, self.damage))

# self.name, self.hp, self.damage 등이 멤버변수이다.
# class 내에서 정의된 변수

# 레이스 : 공중 유닛, 비행기. 클로킹 (상대방에게 보이지 않음)
wraith1 = Unit("레이스", 80, 5)
print("유닛 이름 : {0}, 공격력 : {1}".format(wraith1.name, wraith1.damage))

# 마인드 컨트롤 : 상대방 유닛을 내 것으로 만드는 것 (빼앗음)
wraith2 = Unit("빼앗은 레이스", 80, 5)
wraith2.clocking = True

if wraith2.clocking == True:
    print("{0} 는 현재 클로킹 상태입니다.".format(wraith2.name))
	

9-4. 메소드

# 일반 유닛
class Unit:
    def __init__(self, name, hp, damage):
        self.name = name
        self.hp = hp
        self.damage = damage
        print("{0} 유닛이 생성 되었습니다.".format(self.name))
        print("체력 {0}, 공격력 {1}".format(self.hp, self.damage))

# 공격 유닛
class AttackUnit:
    def __init__(self, name, hp, damage):
        self.name = name
        self.hp = hp
        self.damage = damage
    
    def attack(self, location):
        print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]" \
            .format(self.name, location, self.damage))

    def damaged(self, damage):
        print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage))
        self.hp -= damage
        print("{0} : 현재 체력은 {1} 입니다.".format(self.name, self.hp))
        if self.hp <=0:
            print("{0} : 파괴되었습니다.".format(self.name))

# 메딕 : 의무병

# 파이어뱃 : 공격 유닛, 화염방사기.
firebat1 = AttackUnit("파이어뱃", 50, 16)
firebat1.attack("5시")

# 공격 2번 받는다고 가정
firebat1.damaged(25)
firebat1.damaged(25)

9-5. 상속

class Unit:
    def __init__(self, name, hp):
        self.name = name
        self.hp = hp

# 공격 유닛
class AttackUnit(Unit):
    def __init__(self, name, hp, damage):
        Unit.__init__(self, name, hp) # 상속 받음
        self.damage = damage

    def attack(self, location):
        print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]"\
            .format(self.name, location, self.damage))

    def damaged(self, damage):
        print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage))
        self.hp -= damage
        print("{0} : 현재 체력은 {1} 입니다.".format (self.name, self.hp))
        if self.hp <= 0:
            print("{0} : 파괴되었습니다.".format(self.name))


# 메딕 : 의무병

# 파이어뱃 : 공격 유닛, 화염방사기.
firebat1 = AttackUnit("파이어뱃", 50, 16)
firebat1.attack("5시")

# 공격 2번 받는다고 가정
firebat1.damaged(25)
firebat1.damaged(25)

9-6. 다중 상속

# 일반 유닛
class Unit:
    def __init__(self, name, hp):
        self.name = name
        self.hp = hp

# 공격 유닛
class AttackUnit(Unit):
    def __init__(self, name, hp, damage):
        Unit.__init__(self, name, hp) # 상속 받음
        self.damage = damage

    def attack(self, location):
        print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]" \
            .format(self.name, location, self.damage))

    def damaged(self, damage):
        print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage))
        self.hp -= damage
        print("{0} : 현재 체력은 {1} 입니다.".format(self.name, self.hp))
        if self.hp <=0:
            print("{0} : 파괴되었습니다.".format(self.name))

# 드랍쉽 : 공중 유닛, 수송기. 마린 / 파이어뱃 / 탱크 등을 수송. 공격
# 날 수 있는 기능을 가진 클래스

class Flyable:
    def __init__ (self, flying_speed):
        self.flying_speed = flying_speed

    def fly(self, name, location):
        print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]" \
            .format(name, location, self.flying_speed))

# 공중 공격 유닛 클래스
class FlyableATtackUnit(AttackUnit,Flyable):
    def __init__(self, name, hp, damage, flying_speed):
        AttackUnit.__init__(self, name, hp, damage)
        Flyable.__init__(self, flying_speed)

# 발키리 : 공중 공격 유닛, 한번에 14발 미사일 발사.
valkyrie = FlyableATtackUnit("발키리", 200, 6, 5)
valkyrie.fly(valkyrie.name, "3시") # self.로 들어가는거는 안써줘도 됨
valkyrie = AttackUnit("발키리", 200, 6)
valkyrie.attack("5시")

9-7. 메소드 오버라이딩

# 자식 클래스의 메소드를 사용하고 싶을 때 

# 일반 유닛
class Unit:
    def __init__(self, name, hp, speed):
        self.name = name
        self.hp = hp
        self.speed = speed

    def move(self, location):
        print("[지상 유닛 이동]")
        print("{0} : {1} 방향으로 이동합니다. [속도 {2}]"\
           .format(self.name, location, self.speed))

# 공격 유닛
class AttackUnit(Unit):
    def __init__(self, name, hp, speed, damage):
        Unit.__init__(self, name, hp, speed) # 상속 받음
        self.damage = damage

    def attack(self, location):
        print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]" \
            .format(self.name, location, self.damage))

    def damaged(self, damage):
        print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage))
        self.hp -= damage
        print("{0} : 현재 체력은 {1} 입니다.".format(self.name, self.hp))
        if self.hp <= 0:
            print("{0} : 파괴되었습니다.".format(self.name))

# 드랍쉽 : 공중 유닛, 수송기. 마린 / 파이어뱃 / 탱크 등을 수송. 공격
# 날 수 있는 기능을 가진 클래스
class Flyable:
    def __init__(self, flying_speed):
        self.flying_speed = flying_speed

    def fly(self, name, location):
        print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]" \
            .format(name, location, self.flying_speed))

# 공중 공격 유닛 클래스
class FlyableAttackUnit(AttackUnit, Flyable):
    def __init__(self, name, hp, damage, flying_speed):
        AttackUnit.__init__(self, name, hp, 0, damage) # 지상 speed 0
        Flyable.__init__(self, flying_speed)

    def move(self, location):
        print("[공중 유닛 이동]")
        self.fly(self.name, location)

# 벌쳐 : 지상 유닛, 기동성이 좋음
vulture = AttackUnit("벌쳐", 80, 10, 20)

# 배틀크루저 : 공중 유닛, 체력도 굉장히 좋음, 공격력도 좋음.
battlecruiser = FlyableAttackUnit("배틀크루저", 500, 25, 3)

vulture.move("11시")
battlecruiser.fly(battlecruiser.name, "9시")
battlecruiser.move("9시")

9-8. pass

# 자식 클래스의 메소드를 사용하고 싶을 때

# 일반 유닛
class Unit:
    def __init__(self, name, hp, speed):
        self.name = name
        self.hp = hp
        self.speed = speed

    def move(self, location):
        print("[지상 유닛 이동]")
        print("{0} : {1} 방향으로 이동합니다. [속도 {2}]" \
            .format(self.name, location, self.speed))

# 공격 유닛
class AttackUnit(Unit):
    def __init__(self, name, hp, speed, damage):
        Unit.__init__(self, name, hp, speed) # 상속 받음
        self. damage = damage

    def attack(self, location):
        print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]" \
            .format(self.name, location, self.damage))
    
    def damaged(self, damage):
        print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage))
        self.hp -= damage
        print("{0} : 현재 체력은 {1} 입니다.".format(self.name, self.hp))
        if self.hp <= 0:
            print("{0} : 파괴되었습니다.".format(self.name))

# 드랍쉽 : 공중 유닛, 수송기. 마린 / 파이어뱃 / 탱크 등을 수송. 공격
# 날 수 있는 기능을 가진 클래스
class Flyable:
    def __init__(self, flying_speed):
        self.flying_speed = flying_speed
    
    def fly(self, name, location):
        print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]" \
            .format(name, location, self.flying_speed))

# 공중 공격 유닛 클래스
class FlyableAttackUnit(AttackUnit, Flyable):
    def __init__(self, name, hp, damage, flying_speed):
        AttackUnit.__init__(self, name, hp, 0, damage) # 지상 speed 0
        Flyable.__init__(self, flying_speed)

    def move(self, location):
        print("[공중 유닛 이동]")
        self.fly(self.name, location)

# 건물
class BuildingUnit(Unit):
    def __init__(self, name, hp, location):
        pass # 아무것도 하지 않고 그냥 넘어감

# 서플라이 디폿 : 건물, 1개 건물 = 8 유닛.
supply_depot = BuildingUnit("서플라이 디폿", 500, "7시")

def game_start():
    print("[알림] 새로운 게임을 시작합니다.")

def game_over():
    pass

game_start()
game_over()

9-9. super_practice

class Unit:
    def __init__(self):
        print("Unit 생성자")

class Flyable:
    def __init__(self):
        print("Flyable 생성자")

class FlyableUnit(Unit, Flyable):
    def __init__(self):
        super().__init__()

# 드랍쉽
dropship = FlyableUnit()
-------------------------------------
Unit 생성자
class Unit:
    def __init__(self):
        print("Unit 생성자")

class Flyable:
    def __init__(self):
        print("Flyable 생성자")
        
class FlyableUnit(Flyable, Unit): # 맨 처음에 상속받는 class에 대해서만 init 함수 호출이 된다.
    def __init__(self):
        super().__init__()

dropship = FlyableUnit()
-----------------------------------
Flyable 생성자

super().__init__() 한줄은 
Unit.__init__(self)
Flyable.init__(self) 두줄과 같다.
# 자식 클래스의 메소드를 사용하고 싶을 때

# 일반 유닛
class Unit:
    def __init__(self, name, hp, speed):
        self.name = name
        self.hp = hp
        self.speed = speed

    def move(self, location):
        print("[지상 유닛 이동]")
        print("{0} : {1} 방향으로 이동합니다. [속도 {2}]" \
            .format(self.name, location, self.speed))

# 공격 유닛
class AttackUnit(Unit):
    def __init__(self, name, hp, speed, damage):
        Unit.__init__(self, name, hp, speed) # 상속 받음
        self. damage = damage

    def attack(self, location):
        print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]" \
            .format(self.name, location, self.damage))
    
    def damaged(self, damage):
        print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage))
        self.hp -= damage
        print("{0} : 현재 체력은 {1} 입니다.".format(self.name, self.hp))
        if self.hp <= 0:
            print("{0} : 파괴되었습니다.".format(self.name))

# 드랍쉽 : 공중 유닛, 수송기. 마린 / 파이어뱃 / 탱크 등을 수송. 공격
# 날 수 있는 기능을 가진 클래스
class Flyable:
    def __init__(self, flying_speed):
        self.flying_speed = flying_speed
    
    def fly(self, name, location):
        print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]" \
            .format(name, location, self.flying_speed))

# 공중 공격 유닛 클래스
class FlyableAttackUnit(AttackUnit, Flyable):
    def __init__(self, name, hp, damage, flying_speed):
        AttackUnit.__init__(self, name, hp, 0, damage) # 지상 speed 0
        Flyable.__init__(self, flying_speed)

    def move(self, location):
        print("[공중 유닛 이동]")
        self.fly(self.name, location)

# 건물
class BuildingUnit(Unit):
    def __init__(self, name, hp, location):
        #Unit.__init__(self, name, hp, 0)
        super().__init__(name, hp, 0) # super는 괄호 붙이고, self 안씀
        self.location = location

9-10. 스타크래프트 프로젝트 전반전

# 일반 유닛
class Unit:
    def __init__(self, name, hp, speed):
        self.name = name
        self.hp = hp
        self.speed = speed
        print("{0} 유닛이 생성되었습니다.".format(name))

    def move(self, location):
        print("[지상 유닛 이동]")
        print("{0} : {1} 방향으로 이동합니다. [속도 {2}]" \
            .format(self.name, location, self.speed))
    def damaged(self, damage):
        print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage))
        self.hp -= damage
        print("{0} : 현재 체력은 {1} 입니다.".format(self.name, self.hp))
        if self.hp <= 0:
            print("{0} : 파괴되었습니다.".format(self.name))

# 공격 유닛
class AttackUnit(Unit):
    def __init__(self, name, hp, speed, damage):
        Unit.__init__(self, name, hp, speed) # 상속 받음
        self. damage = damage

    def attack(self, location):
        print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]" \
            .format(self.name, location, self.damage))
    
# 마린
class Marine(AttackUnit):
    def __init__(self):
        AttackUnit.__init__(self, "마린", 40, 1, 5)

    # 스팀팩 : 일정 시간 동안 공격 속도 증가, 체력 10 감소
    def stimpack(self):
        if self.hp > 10:
            self.hp -= 10
            print("{0} : 스팀팩을 사용합니다. (HP 10 감소)".format(self.name))
        else:
            print("{0} : 체력이 부족하여 스팀팩을 사용하지 않습니다.".format(self.name))

# 탱크
class Tank(AttackUnit):
    # 시즈모드 : 탱크를 지상에 고정시켜, 더 높은 파워로 공격 가능. 이동 불가.
    seize_developed = False # 시즈모드 개발여부
    def __init__(self):
        AttackUnit.__init__(self, "탱크", 150, 1, 35)
        self.seize_mode = False
    
    def set_seize_mode(self):
        if Tank.seize_developed == False:
            return
        
        # 현재 시즈모드가 아닐 때 -> 시즈모드
        if self.seize_mode == False:
            print("{0} : 시즈모드로 전환합니다.".format(self.name))
            self.damage *= 2
            self.seize_mode = True
        # 현재 시즈모드일 때 -> 시즈모드 해제
        else:
            print("{0} : 시즈모드를 해제합니다.".format(self.name))
            self.damage /= 2
            self.seize_mode = False

        
# 드랍쉽 : 공중 유닛, 수송기. 마린 / 파이어뱃 / 탱크 등을 수송. 공격
# 날 수 있는 기능을 가진 클래스
class Flyable:
    def __init__(self, flying_speed):
        self.flying_speed = flying_speed
    
    def fly(self, name, location):
        print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]" \
            .format(name, location, self.flying_speed))

# 공중 공격 유닛 클래스
class FlyableAttackUnit(AttackUnit, Flyable):
    def __init__(self, name, hp, damage, flying_speed):
        AttackUnit.__init__(self, name, hp, 0, damage) # 지상 speed 0
        Flyable.__init__(self, flying_speed)

    def move(self, location):
        print("[공중 유닛 이동]")
        self.fly(self.name, location)

# 레이스
class Wraith(FlyableAttackUnit):
    def __init__(self):
        FlyableAttackUnit.__init__(self,"레이스", 80, 20, 5)
        self.clocked = False # 클로킹 모드 (해제 상태)

    def clocking(self):
        if self.clocked == True: # 클로킹 모드 -> 모드 해제
            print("{0} : 클로킹 모드 해제합니다.".format(self.name))
            self.clocked = False
        else: #클로킹 모드 해제 -> 모드 설정
            print("{0} : 클로킹 모드 설정합니다.".format(self.name))
            self.clocked = True
# 건물
class BuildingUnit(Unit):
    def __init__(self, name, hp, location):
        #Unit.__init__(self, name, hp, 0)
        super().__init__(name, hp, 0) # super는 괄호 붙이고, self 안씀
        self.location = location

9-11. 스타크래프트 프로젝트 후반전

from random import *

# 일반 유닛
class Unit:
    def __init__(self, name, hp, speed):
        self.name = name
        self.hp = hp
        self.speed = speed
        print("{0} 유닛이 생성되었습니다.".format(name))

    def move(self, location):
        print("{0} : {1} 방향으로 이동합니다. [속도 {2}]" \
            .format(self.name, location, self.speed))
    def damaged(self, damage):
        print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage))
        self.hp -= damage
        print("{0} : 현재 체력은 {1} 입니다.".format(self.name, self.hp))
        if self.hp <= 0:
            print("{0} : 파괴되었습니다.".format(self.name))

# 공격 유닛
class AttackUnit(Unit):
    def __init__(self, name, hp, speed, damage):
        Unit.__init__(self, name, hp, speed) # 상속 받음
        self. damage = damage

    def attack(self, location):
        print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]" \
            .format(self.name, location, self.damage))
    
# 마린
class Marine(AttackUnit):
    def __init__(self):
        AttackUnit.__init__(self, "마린", 40, 1, 5)

    # 스팀팩 : 일정 시간 동안 공격 속도 증가, 체력 10 감소
    def stimpack(self):
        if self.hp > 10:
            self.hp -= 10
            print("{0} : 스팀팩을 사용합니다. (HP 10 감소)".format(self.name))
        else:
            print("{0} : 체려깅 부족하여 스팀팩을 사용하지 않습니다.".format(self.name))

# 탱크
class Tank(AttackUnit):
    # 시즈모드 : 탱크를 지상에 고정시켜, 더 높은 파워로 공격 가능. 이동 불가.
    seize_developed = False # 시즈모드 개발여부
    def __init__(self):
        AttackUnit.__init__(self, "탱크", 150, 1, 35)
        self.seize_mode = False
    
    def set_seize_mode(self):
        if Tank.seize_developed == False:
            return
        
        # 현재 시즈모드가 아닐 때 -> 시즈모드
        if self.seize_mode == False:
            print("{0} : 시즈모드로 전환합니다.".format(self.name))
            self.damage *= 2
            self.seize_mode = True
        # 현재 시즈모드일 때 -> 시즈모드 해제
        else:
            print("{0} : 시즈모드를 해제합니다.".format(self.name))
            self.damage /= 2
            self.seize_mode = False

        
# 드랍쉽 : 공중 유닛, 수송기. 마린 / 파이어뱃 / 탱크 등을 수송. 공격
# 날 수 있는 기능을 가진 클래스
class Flyable:
    def __init__(self, flying_speed):
        self.flying_speed = flying_speed
    
    def fly(self, name, location):
        print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]" \
            .format(name, location, self.flying_speed))

# 공중 공격 유닛 클래스
class FlyableAttackUnit(AttackUnit, Flyable):
    def __init__(self, name, hp, damage, flying_speed):
        AttackUnit.__init__(self, name, hp, 0, damage) # 지상 speed 0
        Flyable.__init__(self, flying_speed)

    def move(self, location):
        self.fly(self.name, location)

# 레이스
class Wraith(FlyableAttackUnit):
    def __init__(self):
        FlyableAttackUnit.__init__(self, "레이스", 80, 20, 5)
        self.clocked = False # 클로킹 모드 (해제 상태)

    def clocking(self):
        if self.clocked == True: # 클로킹 모드 -> 모드 해제
            print("{0} : 클로킹 모드 해제합니다.".format(self.name))
            self.clocked = False
        else: #클로킹 모드 해제 -> 모드 설정
            print("{0} : 클로킹 모드 설정합니다.".format(self.name))
            self.clocked = True
# 건물
class BuildingUnit(Unit):
    def __init__(self, name, hp, location):
        #Unit.__init__(self, name, hp, 0)
        super().__init__(name, hp, 0) # super는 괄호 붙이고, self 안씀
        self.location = location

def game_start():
    print("[알림] 새로운 게임을 시작합니다.")

def game_over():
    print("Player : gg") # good gmae
    print("[Player] 님이 게임에서 퇴장하셨습니다.")

# 게임 시작
game_start()

# 마린 3기 생성
m1 = Marine()
m2 = Marine()
m3 = Marine()

# 탱크 2기 생성
t1 = Tank()
t2 = Tank()

# 레이스 1기 생성
w1 = Wraith()

# 유닛 일괄 관리 ( 생성된 모든 유닛 append)
attack_units = []
attack_units.append(m1)
attack_units.append(m2)
attack_units.append(m3)
attack_units.append(t1)
attack_units.append(t2)
attack_units.append(w1)

# 전군 이동
for unit in attack_units: 
    unit.move ("1시")

# 탱크 시즈모드 개발
Tank.seize_developed = True
print("[알림] 탱크 시즈 모드 개발이 완료되었습니다.")

# 공격 모드 준비 ( 마린: 스팀팩, 탱크 : 시즈모드, 레이스 : 클로킹)
for unit in attack_units:
    if isinstance(unit, Marine): # 이 유닛이 마린인지 확인
        unit.stimpack()
    elif isinstance(unit, Tank):
        unit.set_seize_mode()
    elif isinstance(unit, Wraith):
        unit.clocking()

# 전군 공격
for unit in attack_units:
    unit.attack("1시")

# 전군 피해
for unit in attack_units:
    unit.damaged(randint(5,21)) # 공격은 랜덤으로 받음 (5 ~ 20)

# 게임 종료
game_over()

9-12. Quiz

Quiz) 주어진 코드를 활용하여 부동산 프로그램을 작성하시오.

(출력 예제)
총 3대의 매물이 있습니다.
강남 아파트 매매 10억 2010년
마포 오피스텔 전세 5억 2007년
송파 빌라 월세 500/50 2000년

[코드]

class House:
    # 매물 초기화
    def __init__(self, location, house_type, deal_type, price,  completion_year):
        self.location = location
        self.house_type = house_type
        self.deal_type = deal_type
        self.price = price
        self.completion_year = completion_year

    # 매물 정보 표시
    def show_detail(self):
        print(self.location, self.house_type, self.deal_type, \
            self.price, self.completion_year)

houses = []
house1 = House("강남", "아파트", "매매", "10억", "2010년")
house2 = House("마포", "오피스텔", "전세", "5억", "2007년")
house3 = House("송파", "빌라", "월세", "500/50", "2000년")
houses.append(house1)
houses.append(house2)
houses.append(house3)

print("총 {0} 대의 매물이 있습니다.".format(len(houses)))
for house in houses:
    house.show_detail()

10-1. 예외처리

try: # try 내부에 있는 문장을 실행하다가 문제가 있을 때 except내부에 있는 명령 실행

    print("나누기 전용 계산기입니다.")
    nums = []
    nums.append(int(input("첫 번째 숫자를 입력하세요: ")))
    nums.append(int(input("두 번째 숫자를 입력하세요: ")))
    nums.append(int(nums[0] / nums[1]))
    print("{0} / {1} = {2}".format(nums[0], nums[1], nums[2]))
except ValueError:
    print("에러! 잘못된 값을 입력하셨습니다.")
except ZeroDivisionError as err:
    print(err)
# except:
#     print("알 수 없는 에러가 발생하였습니다.")
except Exception as err:
    print("알 수 없는 에러가 발생하였습니다.")
    print(err)

10-2. 에러 발생시키기

try:
    print("한 자리 숫자 나누기 전용 계산기입니다.")
    num1 = int(input("첫 번째 숫자를 입력하세요 : "))
    num2 = int(input("첫 번째 숫자를 입력하세요 : "))
    if num1 >= 10 or num2 >= 10:
        raise ValueError
    print("{0} / {1} = {2}".format(num1, num2, int(num1/num2)))
except ValueError:
    print("잘못된 값을 입력하였습니다. 한 자리 숫자만 입력하세요.")

10-3. 사용자 정의 예외처리

class BigNumberError(Exception): # Exception 클래스 상속받음
    def __init__(self, msg):
        self.msg = msg
    
    def __str__(self):
        return self.msg

try:
    print("한 자리 숫자 나누기 전용 계산기입니다.")
    num1 = int(input("첫 번째 숫자를 입력하세요 : "))
    num2 = int(input("첫 번째 숫자를 입력하세요 : "))
    if num1 >= 10 or num2 >= 10:
        raise BigNumberError("입력값 : {0}, {1}".format(num1, num2))
    print("{0} / {1} = {2}".format(num1, num2, int(num1/num2)))
except ValueError:
    print("잘못된 값을 입력하였습니다. 한 자리 숫자만 입력하세요")
except BigNumberError as err:
    print("에러가 발생하였습니다. 한 자리 숫자만 입력하세요.")
    print(err)

10-4. finally

# 무조건 실행되는 구문
class BigNumberError(Exception): # Exception 클래스 상속받음
    def __init__(self, msg):
        self.msg = msg

    def __str__(self):
        return self.msg

try:
    print("한 자리 숫자 나누기 전용 계산기입니다.")
    num1 = int(input("첫 번째 숫자를 입력하세요 :"))
    num2 = int(input("첫 번째 숫자를 입력하세요 :"))
    if num1 >= 10 or num2 >= 10:
        raise BigNumberError("입력값 : {0}, {1}".format(num1, num2))
    print("{0} / {1} = {2}".format(num1, num2, int(num1/num2)))
except ValueError:
    print("잘못된 값을 입력하였습니다. 한 자리 숫자만 입력하세요.")
except BigNumberError as err:
    print("에러가 발생하였습니다. 한 자리 숫자만 입력하세요.")
    print(err)
finally:
    print("계산기를 이용해 주셔서 감사합니다.")

10-5. Quiz

Quiz) 동네에 항상 대기 손님이 있는 맛있는 치킨집이 있습니다.
대기 손님의 치킨 요리 시간을 줄이고자 자동 주문 시스템을 제작하였습니다.
시스템 코드를 확인하고 적절한 예외처리 구문을 넣으시오.

조건1: 1보다 작거나 숫자가 아닌 입력값이 들어올 때는 ValueError 로 처리
출력 메시지 : "잘못된 값을 입력하였습니다."
조건2 : 대기 손님이 주문할 수 있는 총 치킨량은 10마리로 한정
치킨 소진 시 사용자 정의 에러[SoldOutError]를 발생시키고 프로그램 종료
출력 메시지 : "재고가 소진되어 더 이상 주문을 받지 않습니다."

내 코드

# [코드]
class SoldOutError(Exception):
    def __init__(self,msg):
        self.msg = msg

    def __str__(self):
        return self.msg

try:
    chicken = 10
    waiting = 1 # 홀 안에는 현재 만석. 대기번호 1부터 시작
    while(True):
        print("[남은 치킨 : {0}]".format(chicken))
        order = int(input("치킨 몇 마리 주문하시겠습니까?"))           
        if order > chicken: # 남은 치킨보다 주문량이 많을때        
            print("재료가 부족합니다.")
            print("[남은 치킨 : {0}]".format(chicken))
            order = int(input("다시 주문을 해주세요: "))
            
        else:
            print("[대기번호 {0}] {1} 마리 주문이 완료되었습니다." \
            .format(waiting, order))
            waiting += 1
            chicken -= order
            if chicken == 0:
                raise SoldOutError("{0}".format(order))
except ValueError:
    print("잘못된 값을 입력하였습니다.")
except SoldOutError as err:
    print("재고가 소진되어 더 이상 주문을 받지 않습니다.")

나도코딩 코드

class SoldOutError(Exception):
    pass

chicken = 10
waiting = 1 # 홀 안에는 현재 만석. 대기번호 1부터 시작
while(True):
    try:
        print("[남은 치킨 : {0}]".format(chicken))
        order = int(input("치킨 몇 마리 주문하시겠습니까?"))           
        if order > chicken: # 남은 치킨보다 주문량이 많을때        
            print("재료가 부족합니다.")
        elif order <= 0:
            raise ValueError
        else:
            print("[대기번호 {0}] {1} 마리 주문이 완료되었습니다." \
            .format(waiting, order))
            waiting += 1
            chicken -= order

        if chicken == 0:
            raise SoldOutError
    except ValueError:
        print("잘못된 값을 입력하였습니다.")
    except SoldOutError:
        print("재고가 소진되어 더 이상 주문을 받지 않습니다.")
        break

11-1. 모듈

theater_module.py

# 일반 가격
def price(people):
    print("{0}명 가격은 {1}원 입니다.".format(people, people * 10000))

# 조조할인 가격
def price_morning(people):
    print("{0}명 조조 할인 가격은 {1}원 입니다.".format(people, people * 6000))

# 군인 할인 가격
def price_soldier(people):
    print("{0}명 군인 할인 가격은 {1}원 입니다.".format(people, people * 4000))
import theater_module
theater_module.price(3) # 3명이서 영화 보러 갔을 때 가격
theater_module.price_morning(4) # 4명이서 조조 할인 영호 보러 갔을 때
theater_module.price_soldier(5) # 5명의 군인이 영화 보러 갔을 때

import theater_module as mv # as 쓰면 theater_module을 mv로만 호출 가능
mv.price(3)
mv.price_morning(4)
mv.price_soldier(5)

from theater_module import* # 전체 기능 불러옴
price(3)
price_morning(4)
price_soldier(5)

from theater_module import price, price_morning # module 불러서 price, price_morning만 꺼냄
price(5)
price_morning(6)
price_soldier(7)

from theater_module import price_soldier as price
price(5)

11-2. 패키지

travel 폴더 내 init.py, thailand.py, vietnam.py

init.py

__all__ = ["vietnam", "thailand"]

thailand.py

class ThailandPackage:
    def detail(self):
        print("[태국 패키지 3박 5일] 방콕, 파타야 여행 (야시장 투어) 50만원")

if __name__ == "__main__":
    print("Thailand 모듈을 직접 실행")
    print("이 문장은 모듈을 직접 실행할 때만 실행돼요")
    trip_to = ThailandPackage()
    trip_to.detail()
else:
    print("Thailand 외부에서 모듈 호출")

vietnam.py

class VietnamPackage:
    def detail(self):
        print("[베트남 패키지 3박 5일] 다낭 효도 여행 60만원")

패키지.py

import travel.thailand
# import travel.thailand.ThailandPackage() 이런식으로는 사용 불가
trip_to = travel.thailand.ThailandPackage()
trip_to.detail()

from travel.thailand import ThailandPackage
trip_to = ThailandPackage()
trip_to.detail()

from travel import vietnam
trip_to = vietnam.VietnamPackage()
trip_to.detail()

11-3. all

from travel import * # *은 travel 안의 모든 것을 가져오겠다 라는 말, 개발자가 공개 범위를 설정 해줘야 함 ()
# trip_to = vietnam.VietnamPackage()
# trip_to.detail()
trip_to = thailand.ThailandPackage()
trip_to.detail()

11-4. 모듈 직접 실행

thailand.py

class ThailandPackage:
    def detail(self):
        print("[태국 패키지 3박 5일] 방콕, 파타야 여행 (야시장 투어) 50만원")

if __name__ == "__main__":
    print("Thailand 모듈을 직접 실행")
    print("이 문장은 모듈을 직접 실행할 때만 실행돼요")
    trip_to = ThailandPackage()
    trip_to.detail()
else:
    print("Thailand 외부에서 모듈 호출")

11-5. 패키지, 모듈 위치

from travel import *
import inspect
import random
print(inspect.getfile(random)) # random 모듈이 어디에 있는지 위치를 찾아줌
print(inspect.getfile(thailand))

11-6. pip install

  1. 구글에 pypi 검색
  2. 검색창에 원하는 pip 검색 ex) beautifulsoup
  3. 코드 복사한 후 터미널에 입력
    ex) pip install beautifulsoup4
  4. 설치 후 사용

11-7. 내장함수

# input : 사용자 입력을 받는 함수
language = input("무슨 언어를 좋아하세요?")
print("{0}은 아주 좋은 언어입니다!".format(language))

# dir : 어떤 객체를 넘겨줬을 때 그 객체가 어떤 변수와 함수를 가지고 있는지 표시
print(dir())
import random # 외장 함수
print(dir())
import pickle
print(dir())

print(dir(random))
# random. 했을 때 사용할 수 있는것들 리스트가 나옴

lst = [1, 2, 3]
print(dir(lst))

name = "Jim"
print(dir(name)) # 구글에 list of python builtins 검색

11-8. 외장함수

# 구글에 list of python modules 검색
# glob : 경로 내의 폴더 / 파일 목록 조회 (윈도우 dir)
import glob
print(glob.glob("*.py")) # 확장자가 py인 모든 파일

# os : 운영체제에서 제공하는 기본 기능
import os
print(os.getcwd()) # 현재 디렉토리 위치

folder = "sample_dir"

if os.path.exists(folder):
    print("이미 존재하는 폴더입니다.")
    os.rmdir(folder)
    print(folder, "폴더를 삭제하였습니다.")
else:
    os.makedirs(folder) # 폴더생성
    print(folder, "폴더를 생성하였습니다.")

print(os.listdir()) # glob과 비슷한 기능, 디렉토리 파일, 폴더 존재하는 내용 표시

# time : 시간 관련 함수
import time
print(time.localtime())
print(time.strftime("%Y-%m-%d %H:%M:%S"))

import datetime
print("오늘 날짜는", datetime.date.today())

# timedelta : 두 날짜 사이의 간격
today = datetime.date.today() # 오늘 날짜 저장
td = datetime.timedelta(days=100) # 100일 저장
print("우리가 만난지 100일은", today + td) # 오늘부터 100일 후

11-9. Quiz

Quiz) 프로젝트 내에 나만의 시그니처를 남기는 모듈을 만드시오

조건 : 모듈 파일명은 byme.py 로 작성

(모듈 사용 예제)
import byme
byme.sign()

(출력 예제)
이 프로그램은 나도코딩에 의해 만들어졌습니다.
유튜브 : http://youtube.com
이메일 : nadocoding@gmail.com

import byme
byme.sign()

byme.py

def sign():
    print("이 프로그램은 나도코딩에 의해 만들어졌습니다.")
    print("유튜브 : http://youtube.com")
    print("이메일 : nadocoding#@gmail.com")
profile
공부일기

0개의 댓글