# Member variable

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)

 

 레이스 : 공중 유닛, 비행기. 클로킹 (상대방에게 보이지 않음)

wraith1 = Unit("레이스", 80, 5)

 클래스안에 있는 변수들을 외부에서 접근이 가능하다.

print("유닛 이름 : {0}, 공격력 : {1}".format(wraith1.name, wraith1.damage))

 

 마인드 컨트롤 : 상대방 유닛을 내 것으로 만드는 것 (빼앗음)

wraith2 = Unit("빼앗은 레이스", 80, 5)

 클래스 내부에 init에 새로운 값을 추가 할 수가 있다.

 wraith1에서는 clocking 값이 false이므로 접근 불가능.

wraith2.clocking = True

 

if wraith2.clocking == True:

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

'Python' 카테고리의 다른 글

Python-상속  (0) 2020.07.05
Python-Method  (0) 2020.07.05
Python Class  (0) 2020.07.05
Python 함수  (0) 2020.07.05
Python 제어문  (0) 2020.07.05

 class는 붕어빵틀이라고 생각하면 된다.

 마린 : 공격 유닛, 군인. 총을 쏠 수 있음

 name = "마린"  # 유닛의 이름

 hp = 40  # 유닛의 체력

 damage = 5  # 유닛의 공격력

 

 print("{0} 유닛이 생성되었습니다.".format(name))

 print("체력 {0}, 공격력 {1}\n".format(hp, damage))

 

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

 tank_name = "탱크"

 tank_hp = 150

 tank_damage = 35

 

 print("{0} 유닛이 생성되었습니다.".format(tank_name))

 print("체력 {0}, 공격력 {1}\n".format(tank_hp, tank_damage))

 

 tank2_name = "탱크2"

 tank2_hp = 150

 tank2_damage = 35

 

 print("{0} 유닛이 생성되었습니다.".format(tank2_name))

 print("체력 {0}, 공격력 {1}\n".format(tank_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

        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)

'Python' 카테고리의 다른 글

Python-Method  (0) 2020.07.05
Python - Member 변수  (0) 2020.07.05
Python 함수  (0) 2020.07.05
Python 제어문  (0) 2020.07.05
Python data_structure  (1) 2020.06.29

함수사용법

def 함수명(인자값):

     실행문

     return (반환값이 필요한 경우)

 

실행시 : 함수명(인자값)

 

함수의 전달값과 반환값

def open_account():

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



open_account()



def deposit(balance, money):  # 입금

    print("입금이 완료되었습니다. 잔액은 {0}원입니다.".format(balance + money))

    return balance + money



def withdraw(balance, money):  # 출금

    if balance > money:  # 잔액이 출금보다 많으면

        print("출금이 완료되었습니다. 잔액은 {0}원입니다.".format(balance - money))

        return balance - money

    else:

        print("출금이 완료되지 않았습니다. 잔액은 {0}원입니다.".format(balance))



def withdraw_night(balance, money):  # 저녁에 출금

    commission = 100  # 수수료 100원

    return commission, balance - money - commission  # 튜플 형식으로 반환



balance = 0  # 잔액

balance = deposit(balance, 1000)

print(balance)

 

# balance = withdraw(balance, 2000)

# balance = withdraw(balance, 500)

 

commission, balance = withdraw_night(balance, 500)

print("수수료는 {0}원이며, 잔액은 {1}원입니다.".format(commission, balance))

 

 

함수의 기본값

 def proflie(name, age, main_lang):

     print("이름 : {0}\t 나이 : {1}\t 주 사용언어: {2}"

           .format(name, age, main_lang))



 proflie("홍길동", 12, "파이썬")

 proflie("김태호", 15, "자바")

 

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

 

def proflie(name, age=17, main_lang="파이썬"):

    print("이름 : {0}\t 나이 : {1}\t 주 사용언어: {2}"

          .format(name, age, main_lang))



proflie("강원도")

proflie("김태호")

 

함수의 키워드 값

def profile(name, age, main_lang):

    print(name, age, main_lang)



profile(name="유재석", main_lang="파이썬", age=20)

profile(main_lang="파이썬", age=20, name="유재석")

 

함수의 가변인자

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#", "Node.js")

profile("김태호", 25, "Kotlin", "Swift")

 

함수의 지역변수와 전역변수

gun = 10



def checkpoint(soldiers):  # 경계근무

    global gun  # 전역 공간에 있는 gun 사용

    gun = gun - soldiers

    print("[함수 내] 남은 총 : {0}".format(gun))



def checkpoint_ret(gun, soldiers):

    gun = gun - soldiers

    print("[함수 내] 남은 총 : {0}".format(gun))

    return gun



print("전체 총 : {0}".format(gun))

# checkpoint(2)  # 2명이 경계 근무 나감

gun = checkpoint_ret(gun, 2)

print("남은 총 : {0}".format(gun))

 

'Python' 카테고리의 다른 글

Python - Member 변수  (0) 2020.07.05
Python Class  (0) 2020.07.05
Python 제어문  (0) 2020.07.05
Python data_structure  (1) 2020.06.29
Python 문자열  (0) 2020.06.29

제어문 IF

 if 조건:

     실행 명령문

weather = input("오늘 날씨는 어때요? ")

 

 if weather == "비" or weather == "눈":

     print("우산을 챙기세요")

 elif weather == "미세먼지":

     print("마스크를 챙기세요")

 else:

    print("준비물 필요 없어요.")

 

print("---------------------------------")

 

 temp = int(input("기온은 어때요? "))

 if 30 <= temp:

     print("너무 더워요. 나가지 마세요")

 elif 10 <= temp and temp < 30:

     print("괜찮은 날씨예요")

 elif 0 <= temp < 10:

     print("외투를 챙기세요")

 else:

     print("너무 추워요. 나가지 마세요")



 for 반복문

 for 변수명 in 반복할 배열구조내용 [내용1, 내용2, 내용3]

 

 for waiting_no in [0, 1, 2, 3, 4]:

     print("대기번호 : {0}" .format(waiting_no))

 

 print("--------------------------------------")

 

 for waiting_no in range(1, 6):  # 1, 2, 3, 4, 5

     print("대기번호 : {0}" .format(waiting_no))

 

 starbucks = ["아이언맨", "토르", "아이엠 그루트"]

 for customer in starbucks:

     print("{0}, 커피가 준비되었습니다." .format(customer))

 

print("--------------------------------------")

 

 while

 while 조건 :

    실행문

 customer = "토르"

 index = 5

 while index >= 1:

     print("{0}, 커피가 준비 되었습니다. {1} 번 남았어요".format(customer, index))

     index -= 1

     if index == 0:

         print("커피는 폐기처분되었습니다.")

 

 

while문 무한 반복(조건이 계속 참이기때문에)

 customer = "아이언맨"

 index = 1

 while True:

     print("{0}, 커피가 준비 되었습니다. 호출{1} 회".format(customer, index))

     index += 1

 

while문 특정조건의 값이 들어올때만 실행됨

 customer = "토르"

 person = "Unknown"

 

 while person != customer:

     print("{0}, 커피가 준비 되었습니다".format(customer))

     person = input("이름이 어떻게 되세요? ")

 

# print("--------------------------------------")

 

 continue 와 break

 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))

         break

     print("{0}, 책을 읽어봐".format(student))



 한줄 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)

'Python' 카테고리의 다른 글

Python Class  (0) 2020.07.05
Python 함수  (0) 2020.07.05
Python data_structure  (1) 2020.06.29
Python 문자열  (0) 2020.06.29
Python 연산자  (2) 2020.06.29

+ Recent posts