[TIL#7]Pythonベース-3
Table of Contents
1.基本文法
1.基本文法
print("python", "java", "javascript" ,sep=" vs ", end=" ? ") # sep사용하면 두 문자 사이를 , / vs 등을 지정할 수 있다. end는 문장의 끝부분을 ?로 나타내달라. 그리고 뒤의 문장를 한문장으로 출력
print("which one is more fune?")
import sys
print("python", "java", "javascript" ,file=sys.stdout) # 표준출력으로 문장이 찍히는 것임.
print("python", "java", "javascript" ,file=sys.stderr) # 표준에러로 처리가 되는 것임.
scores = {"math" :0, "english": 50, "coding": 100}
for subject, score in scores.items(): # items는 key(여기서는 subject) 와 value(score)로 turple로 보내줌.
print(subject.ljust(8), str(score).rjust(4),sep=":") # subject는 .ljust를 사용하여 왼쪽 정렬 하는데 8칸을 확보 score 부분은 .rjust는 오른쪽 정렬 하는데 4칸의 공간을 확보
for num in range(1, 21):
print ("waiting number :" +str(num).zfill(3)) # 3개만큼의 공간을 확보해서 숫자를 보여주게하는 방법 값이 없을댄 0이 출력됨.
answer = input("please input anything:") # input을 통해서 값을 받으면 항상 문자열형태로 출력됨. 10일 넣어도 str 임.
print("입력하신 값은 " + answer + "입니다.")
# 빈 자리는 빈공간으로 두고, 오른쪽 정렬을 하되, 총 10자리 공간을 확보
print("{0: >10}".format(-5000))
# 양수일때는 + 로 표시 음수일때는 -로 표시
print("{0: >+10}".format(500))
print("{0: >+10}".format(-500))
# 왼쪽 정렬하고 빈칸을 _로 채움
print("{0:_<+10}".format(5000))
# 3자리 마다 , 표시
print("{0:,}".format(5000000))
# 3자리 마다 , 표시 +- 부호도 표시
print("{0:+,}".format(5000000))
print("{0:-,}".format(-5000000))
# 3자리 마다 , 표시 +- 부호도 표시, 자리수도 확보하기 빈자리는 ^ 로 표시.
print("{0:^<+30,}".format(5000))
# 소수점 출력
print("{0:f}".format(5/3))
# 소수점 출력을 특정자리수까지
print("{0:.7f}".format(5/3))
score_file = open("score.txt","w", encoding="utf8") # score_file 을 쓰기 목적으로 열어서 ("w") utf8을 입력하지 않으면 한글이 이상한 문자로 표기. # file 을 열었으면 닫아줘여함 .
print("math : 0", file=score_file)
print("english : 50", file=score_file)
score_file.close()
score_file = open("score.txt","a", encoding="utf8") # a는 append를 나타냄. 추가함.
score_file.write("science : 80")
score_file.write("\n conding : 100")
score_file.close()
score_file = open("score.txt", "r", encoding="utf8") # r 은 read.
print(score_file.read()) # read는 전체 다 읽음
score_file.close
score_file = open("score.txt", "r", encoding="utf8") # r 은 read.
print(score_file.readline())
print(score_file.readline())
print(score_file.readline())
print(score_file.readline()) # 한줄만 읽음
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: # lines list에서 한줄씩 불러와서 출력
print(line, end="")
score_file.close()
# pickle 이란 프로그램상 사용하는 데이터를 파일로 저장. 다른 사림 이 파일을 사용할 수 있음.
import pickle
profile_file = open("profile.pickle", "wb") # w는 쓰기 이며 "b" 는 binary 라고 하며 pickle을 쓰기 위해서는 입력해야함.
profile = {"name" : "park", "age" : 30, "hobby" : ["soccer", "golf", "coding"]}
print(profile)
pickle.dump(profile, profile_file) # profile에 있는 정보를 file 에 저장
profile_file.close()
profile_file = open("profile.pickle", "rb")
profile = pickle.load(profile_file) # file에 있는 정보를 profile 에 불러오기.
print(profile)
profile_file.close()
import pickle
with open("profile.pickle","rb") as profile_file: # with open (' 파일명','w') as 변수명
print(pickle.load(profile_file)) # 변수명.write("내용") 은 파일 쓰기 /with를 쓰면 close 를 해줄 필요 없음
with open("study.txt", "w", encoding= "utf8") as study_file: # write 모드는 실행할 때마다 내용을 덮어쓴다.
study_file.write("파이썬을 열심히 공부하고 있어요.")
with open("study.txt", "r", encoding= "utf8") as study_file:
print(study_file.read())
-Quizimport pickle
for i in range(1, 3):
with open(str(i) + "주차. txt","w",encoding="utf8") as report_file: # n 주차 파일을 만들기 위한 방법 i로 range 값 지정
report_file.write("- {0} 주차 주간보고 - ".format(i))
report_file.write("\n부서: ")
report_file.write("\n이름: ")
report_file.write("\n업무요약: ")
classはフナの餅の型にすればいい.
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) # marine1은 객채이며, unit class 의 instance라고 한다.
marine2 = unit("마린", 40, 5)
tank = unit("탱크", 150, 35)
__init__
これはpythonで使用されるコンストラクション関数です.クラスがインスタンスを作成するときに呼び出す特別な方法.Init前後はPython自動呼び出しのいくつかの方法です.メンバー変数
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) # marine1은 객채이며, unit class 의 instance라고 한다.
marine2 = unit("마린", 40, 5)
tank = unit("탱크", 150, 35)
wraith1 = unit("레이스", 80, 5)
print("유닛이름:{0}, 공격력:{1}". format(wraith1.name, wraith1.damage))
wraith2 = unit("mindcontrol레이스", 80, 5)
wraith2.clocking = True
if wraith2.clocking == True:
print("{0} 는 현재 클로킹 상태입니다.".format(wraith2.name))
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시")
firebat1.damaged(25)
firebat1.damaged(25)
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) #unit class 에서 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시")
firebat1.damaged(25)
firebat1.damaged(25)
class unit: # 부모클래스
def __init__(self, name, hp):
self.name = name
self.hp = hp
class attackunit(unit): #자식클래스 # unit을 상속받음
def __init__(self, name, hp, damage):
unit.__init__(self, name, hp) #unit class 에서 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): # flyable & attackunit class 를 상속받음
def __init__(self, name, hp, damage, flying_speed):
attackunit.__init__(self, name, hp, damage)
flyable.__init__(self, flying_speed)
valkyrie = flyableattackunit("발키리", 200, 6, 5)
valkyrie.fly(valkyrie.name,"3시")
class buildingunit(unit):
def __init__(self, name, hp, location):
pass # 아무것도 안하고 일단 넘어간다. 완성은 한것 아님.
supply_depot = buildingunit("서플라이디폿", 500,"7시")
def game_start():
print("[알림] 새로운 게임을 시작합니다.")
def game_over():
pass
game_start()
game_over()
class buildingunit(unit):
def __init__(self, name, hp, location):
#unit.__init__(self, name, hp, 0)
super.()__init__(name,hp,0) # unit 통해서 할수도 있고 self를 쓰지 않는다. 부모 클래스 초기화하는 법 / super 를 통해서 다중상속을 받으면 맨 마지막 상속값은 상속을 받지 못한다.
self.locaiton = location
from random import *
class unit: # 부모클래스
def __init__(self, name, hp, speed):
self.name = name # 맴버변수
self.hp = hp
self.speed = speed
print("{0} 유닛이 생성되었습니다.". format(self.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): #자식클래스 # unit을 상속받음
def __init__(self, name, hp, speed, damage):
unit.__init__(self, name, hp, speed) #unit class 에서 name 과 hp 값을 가져옴.
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)
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 # sieze mode 라는 맴버변수
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): # flyable & attackunit class 를 상속받음
def __init__(self, name, hp, damage, flying_speed):
attackunit.__init__(self, name, hp,0, damage) # unit 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 #(cloking 모드 해제 상태)
def clocking(self):
if self.clocked == True: # clocking mode -> non clocking mode
print("{0} : 클로킹 모드 해제 합니다.".format(self.name))
self.clocked == False
else: # non clocking mode -> clocking mode
print("{0} : 클로킹 모드 설정 합니다.".format(self.name))
self.clocked == True
def game_start():
print("[알림] 새로운 게임을 시작합니다.")
def game_over():
print("player : gg")
print("[player] 님이 게임에서 퇴장하셨습니다.")
# 실제게임
game_start()
m1 = marine()
m2 = marine()
m3 = marine()
t1 = tank ()
t2 = tank ()
w1 = wraith()
# unit 일관 관리 하기 위해서 attack_units list 만들고 appedn 하여 모든 유닛 삽입.
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: # attack_units에 있는 모든 unit 선택
unit.move ("1시") # move 함수 통해서 이동시킴.
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))
game_over()
依存関係は下図のようになります.-Quiz
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): # show detail함수를 만든다.
print(self.location, self.house_type, self.deal_type, self.price, self.completion_year)
houses =[] # list를 생성한다.
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()
Reference
この問題について([TIL#7]Pythonベース-3), 我々は、より多くの情報をここで見つけました https://velog.io/@junchi211/TIL7-Python-기초-3テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol