<파이썬 코딩 무료 강의 (기본편) - 6시간 뒤면 여러분도 개발자가 될 수 있어요 [나도코딩]>을 보면서 정리한 내용입니다.
클래스
1. 클래스
# # 마린 : 공격 유닛, 군인. 총을 쏠 수 있음
# 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
# 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
print("{0} 유닛이 생성되었습니다.".format(self.name))
print("체력 {0}, 공격력 {1}".format(self.hp, self.damage))
marine1 = Unit("마린", 40, 5) # 클래스의 인스턴스
marine2 = Unit("마린", 40, 5)
tank = Unit("탱크", 150, 35)
2. 멤버변수
# 레이스 : 공중 유닛, 비행기. 클로킹 (상대방에게 보이지 않음)
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))
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))
class AttackUnit:
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))
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)
'''
파이어뱃 유닛이 생성되었습니다.
체력 50, 공격력 16
파이어뱃 : 5시 방향으로 적군을 공격합니다. [공격력 16]
파이어뱃 : 25 데미지를 입었습니다.
파이어뱃 : 현재 체력은 25 입니다.
파이어뱃 : 25 데미지를 입었습니다.
파이어뱃 : 현재 체력은 0 입니다.
파이어뱃 : 파괴되었습니다.
'''
4. 상속
# 일반 유닛
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)
'''
파이어뱃 : 5시 방향으로 적군을 공격합니다. [공격력 16]
파이어뱃 : 25 데미지를 입었습니다.
파이어뱃 : 현재 체력은 25 입니다.
파이어뱃 : 25 데미지를 입었습니다.
파이어뱃 : 현재 체력은 0 입니다.
파이어뱃 : 파괴되었습니다.
'''
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))
# 드랍십 : 공중 유닛, 수송기. 마린 / 파이어뱃 / 탱크 등을 수송. 공격 X
class Flayable:
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, Flayable):
def __init__(self, name, hp, damage, flying_speed):
AttackUnit.__init__(self, name, hp, damage) # 공격유닛에게서 상속받음
Flayable.__init__(self, flying_speed) # 비행유닛에게서 상속받음
# 발키리 : 공중 공격 유닛, 한 번에 14발 미사일 발사.
valkyrie = FlyableAttackUnit("발키리", 200, 6, 5)
valkyrie.fly(valkyrie.name, "3시")
# 발키리 : 3시 방향으로 날아갑니다. [속도 5]
6. 메소드 오버라이딩
class Unit:
def __init__(self, name, hp, speed):
self.name = name
self.hp = hp
self.speed = speed
def move(self, location): # method overriden
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 Flayable:
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, Flayable):
def __init__(self, name, hp, damage, flying_speed):
AttackUnit.__init__(self, name, hp, 0, damage) # 지상 스피드 0
Flayable.__init__(self, flying_speed)
def move(self, location): # method overriding
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시") # fly가 아닌 move 함수 사용
'''
발키리 : 3시 방향으로 날아갑니다. [속도 5]
[지상 유닛 이동]
벌쳐 : 11시 방향으로 이동합니다. [속도 10]
[공중 유닛 이동]
배틀크루저 : 9시 방향으로 날아갑니다. [속도 3]
'''
7. 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 Flayable:
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, Flayable):
def __init__(self, name, hp, damage, flying_speed):
AttackUnit.__init__(self, name, hp, 0, damage) # 지상 스피드 0
Flayable.__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()
8. Super
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 Flayable:
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, Flayable):
def __init__(self, name, hp, damage, flying_speed):
AttackUnit.__init__(self, name, hp, 0, damage) # 지상 스피드 0
Flayable.__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.location = location
class Unit:
def __init__(self):
print("Unit 생성자")
class Flyable:
def __init__(self):
print("Flyable 생성자")
class FlyableUnit(Unit, Flyable):
def __init__(self):
# super().__init__() # super로 다중 상속 시 뒤쪽에 기재한 클래스의 초기화가 되지 않음
Unit.__init__(self)
Flyable.__init__(self)
# 드랍쉽
dropship = FlyableUnit()
'''
Unit 생성자
Flyable 생성자
'''
9. 스타크래프트 프로젝트
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 Flayable:
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, Flayable):
def __init__(self, name, hp, damage, flying_speed):
AttackUnit.__init__(self, name, hp, 0, damage) # 지상 스피드 0
Flayable.__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
def game_start():
print("[알림] 새로운 게임을 시작합니다.")
def game_over():
print("Player : gg")
print("[Player] 님이 게임에서 퇴장하셨습니다.")
# 실제 게임 진행
game_start()
# 마린 3기 생성
m1 = Marine()
m2 = Marine()
m3 = Marine()
t1 = Tank()
t2 = Tank()
# 레이스 1기 생성
w1 = Wraith()
# 유닛 일괄 관리
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()
'''
[알림] 새로운 게임을 시작합니다.
마린 유닛이 생성되었습니다.
마린 유닛이 생성되었습니다.
마린 유닛이 생성되었습니다.
탱크 유닛이 생성되었습니다.
탱크 유닛이 생성되었습니다.
레이스 유닛이 생성되었습니다.
마린 : 1시 방향으로 이동합니다. [속도 1]
마린 : 1시 방향으로 이동합니다. [속도 1]
마린 : 1시 방향으로 이동합니다. [속도 1]
탱크 : 1시 방향으로 이동합니다. [속도 1]
탱크 : 1시 방향으로 이동합니다. [속도 1]
레이스 : 1시 방향으로 날아갑니다. [속도 5]
[알림] 탱크 시즈 모드 개발이 완료되었습니다.
마린 : 스팀팩을 사용합니다. (HP 10 감소)
마린 : 스팀팩을 사용합니다. (HP 10 감소)
마린 : 스팀팩을 사용합니다. (HP 10 감소)
탱크 : 시즈모드로 전환합니다.
탱크 : 시즈모드로 전환합니다.
레이스 : 클로킹 모드 설정합니다.
마린 : 1시 방향으로 적군을 공격합니다. [공격력 5]
마린 : 1시 방향으로 적군을 공격합니다. [공격력 5]
마린 : 1시 방향으로 적군을 공격합니다. [공격력 5]
탱크 : 1시 방향으로 적군을 공격합니다. [공격력 70]
탱크 : 1시 방향으로 적군을 공격합니다. [공격력 70]
레이스 : 1시 방향으로 적군을 공격합니다. [공격력 20]
마린 : 14 데미지를 입었습니다.
마린 : 현재 체력은 16 입니다.
마린 : 7 데미지를 입었습니다.
마린 : 현재 체력은 23 입니다.
마린 : 15 데미지를 입었습니다.
마린 : 현재 체력은 15 입니다.
탱크 : 10 데미지를 입었습니다.
탱크 : 현재 체력은 140 입니다.
탱크 : 21 데미지를 입었습니다.
탱크 : 현재 체력은 129 입니다.
레이스 : 13 데미지를 입었습니다.
레이스 : 현재 체력은 67 입니다.
Player : gg
[Player] 님이 게임에서 퇴장하셨습니다.
'''
Q8. 주어진 코드를 활용하여 부동산 프로그램을 작성하시오.
(출력 예제)
총 3대의 매물이 있습니다.
강남 아파트 매매 10억 2010년
마포 오피스텔 전세 5억 2007년
송파 빌라 월세 500/50 2000년
A1)
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 = []
h1 = House("강남", "아파트", "매매", "10억", "2010년")
h2 = House("마포", "오피스텔", "전세", "5억", "2007년")
h3 = House("송파", "빌라", "월세", "500/50", "2000년")
houses.append(h1)
houses.append(h2)
houses.append(h3)
print("총 {0}대의 매물이 있습니다.".format(len(houses)))
for house in houses:
House.show_detail(house)
예외처리
1. 예외처리
try:
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 Exception as err:
print("알 수 없는 에러가 발생하였습니다.")
print(err)
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("잘못된 값을 입력하였습니다. 한 자리 숫자만 입력하세요.")
3. 사용자 정의 예외처리
class BigNumberError(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)
4. finally
class BigNumberError(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("계산기를 이용해주셔서 감사합니다.") # 정상 작동이든 에러이든 최종적으로 출력됨
Q9. 동네에 항상 대기 손님이 있는 맛있는 치킨집이 있습니다.
대기 손님의 치킨 요리 시간을 줄이고자 자동 주문 시스템을 제작하였습니다.
시스템 코드를 확인하고 적절한 예외처리 구문을 넣으시오.
조건1 : 1보다 작거나 숫자가 아닌 입력값이 들어올 때는 ValueError 로 처리
출력 메시지: "잘못된 값을 입력하였습니다."
조건2 : 대기 손님이 주문할 수 있는 총 치킨량은 10마리로 한정
치킨 소진 시 사용자 정의 에러[SoldOutError]를 발생시키고 프로그램 종료
출력 메시지: "재고가 소진되어 더 이상 주문을 받지 않습니다."
A1)
chicken = 10
waiting = 1 # 홀 안에는 현재 만석. 대기번호 1부터 시작
class SoldOutError(Exception):
pass
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
모듈
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명 가격은 30000원 입니다.
theater_module.price_morning(4) # 4명 조조 할인 가격은 24000원 입니다.
theater_module.price_soldier(5) # 5명 군인 가격은 20000원 입니다.
import theater_module as 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
price(5)
price_morning(6)
# price_soldier는 불러오지 않아 사용 불가
from theater_module import price_soldier as ps
ps(5) # 5명 군인 가격은 20000원 입니다.
2. 패키지
# travel 폴더 만든 후 thailand.py로 저장
class ThailancPackage:
def detail(self):
print("[태국 패키지 3박 5일] 방콕, 파타야 여행 (야시장 투어) 50만원")
# travel 폴더 만든 후 vietnam.py로 저장
class VeitnamPackage:
def detail(self):
print("[베트남 패키지 3박 5일] 다낭 효도 여행 60만원")
import travel.thailand
# import travel.thailand.ThailandPackage 이런 식으로는 사용 불가
trip_to = travel.thailand.ThailancPackage()
trip_to.detail() # [태국 패키지 3박 5일] 방콕, 파타야 여행 (야시장 투어) 50만원
from travel.thailand import ThailancPackage
trip_to = ThailancPackage()
trip_to.detail() # [태국 패키지 3박 5일] 방콕, 파타야 여행 (야시장 투어) 50만원
from travel import vietnam
trip_to = vietnam.VeitnamPackage()
trip_to.detail() # [베트남 패키지 3박 5일] 다낭 효도 여행 60만원
from travel import *
trip_to = vietnam.VeitnamPackage() # 오류! vietnam을 불러올 수 없음
trip_to.detail()
3. __all__
# travel 폴더 만든 후 __init__.py로 저장
__all__ = ["vietnam", "thailand] # 공개 설정
from travel import *
trip_to = vietnam.VeitnamPackage()
trip_to.detail()
4. 모듈 직접 실행
# thailand.py 파일을 직접 실행
class ThailancPackage:
def detail(self):
print("[태국 패키지 3박 5일] 방콕, 파타야 여행 (야시장 투어) 50만원")
if __name__ == "__main__":
print("Thailand 모듈을 직접 실행")
print("이 문장은 모듈을 직접 실행할 때만 실행돼요")
trip_to = ThailancPackage()
trip_to.detail()
else:
print("Thailand 외부에서 모듈 호출")
'''
Thailand 모듈을 직접 실행
이 문장은 모듈을 직접 실행할 때만 실행돼요
[태국 패키지 3박 5일] 방콕, 파타야 여행 (야시장 투어) 50만원
'''
from travel import *
trip_to = thailand.ThailancPackage()
trip_to.detail()
'''
Thailand 외부에서 모듈 호출
[태국 패키지 3박 5일] 방콕, 파타야 여행 (야시장 투어) 50만원
'''
5. 패키지, 모듈 위치
import inspect
import random
from travel import *
print(inspect.getfile(random)) # C:\Python39\lib\random.py
print(inspect.getfile(thailand)) # c:\pythonworkspace\python_study\travel\thailand.py
# travel 폴더 통째로 random의 경로로 옮기면 타 프로젝트 시에도 똑같이 사용 가능
6. pip install
# Google 'pypi' 검색
# pypi 'beautifulsoup' 검색
# 'pip install beautifulsoup4' 로 설치
from bs4 import BeautifulSoup
soup = BeautifulSoup("<p>Some<b>bad<i>HTML")
print(soup.prettify())
'''
<p>
Some
<b>
bad
<i>
HTML
</i>
</b>
</p>
'''
# pip list 현재 설치된 패키지 리스트
# pip show beautifulsoup4 패키지에 대한 정보
# pip install -- upgrade beautifulsoup4 업그레이드
# pip uninstall beautifulsoup4 패키지 삭제
7. 내장함수
# input : 사용자 입력을 받는 함수
# dir : 어떤 객체를 넘겨줬을 때 그 객체가 어떤 변수와 함수를 가지고 있는지 표시
print(dir())
# ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
import random # 외장 함수
print(dir())
# ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'random']
print(dir(random))
# ['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_floor', '_inst', '_log', '_os', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randbytes', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
lst = [1, 2, 3]
print(dir(lst))
# ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
name = "Jim"
print(dir(name))
# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
# Google 'list of python builtins'
8. 외장함수
# # Google 'list of python modules'
# # glob : 경로 내의 폴더 / 파일 목록 조회 (윈도우 dir)
import glob
print(glob.glob("*.py")) # ['Logistic Regression.py']
# # os : 운영체제에서 제공하는 기본 기능
import os
print(os.getcwd()) # 현재 디렉토리 C:\pythonworkspace
folder = "sample_dir"
if os.path.exists(folder):
print("이미 존재하는 폴더입니다.")
os.rmdir(folder)
print(folder, "폴더를 삭제하였습니다.")
else:
os.makedirs(folder)
print(folder, "폴더를 생성하였습니다.")
print(os.listdir()) # ['.ipynb_checkpoints', '.vscode', 'Logistic Regression.py', 'python_study']
# time : 시간 관련 함수
import time
print(time.localtime())
# time.struct_time(tm_year=2021, tm_mon=10, tm_mday=20, tm_hour=18, tm_min=26, tm_sec=54, tm_wday=2, tm_yday=293, tm_isdst=0
print(time.strftime("%Y-%m-%d %H:%M:%S")) # 2021-10-20 18:28:04
import datetime
print("오늘 날짜는", datetime.date.today()) # 오늘 날짜는 2021-10-20
# timedelta : 두 날짜 사이의 간격
today = datetime.date.today()
td = datetime.timedelta(days=100) # 10일 후
print("우리가 만난지 100일은", today + td) # 우리가 만난지 100일은 2022-01-28
Q10. 프로젝트 내에 나만의 시그니처를 남기는 모듈을 만드시오
조건: 모듈 파일명은 byme.py로 작성
(모듈 사용 예제)
import byme
byme.sign()
A1)
# byme.py로 저장
def sign():
print("This program was made by a-brand-new-life.tistory.com")
import byme
byme.sign()
# This program was made by a-brand-new-life.tistory.com