정리
- 새로운 객체지향이라는 내용을 배웠다. 데이터(속성)과 기능(함수)를 하나로 묶어 "객체"로 다루는 방법이라고 한다. 이해가 잘되지는 않으나 함수를 계속 만들었다보니 어떻게 어떻게 객체지향적(?)으로 코드를 작성은 하고 있다.
- 붕어빵틀과 붕어빵..! 쿠키틀과 쿠키를 잊지말자. 하나의 클래스로 틀을 만들고 계속 해서 값을 찍어낼 수 있게 생각을 하자.
필기
함수복습
- 생각보다 문제가 잘풀렸다. 입력, 계산까지는 잘하는데 마지막 출력에서 버벅인다. 출력에서 항상 뭐가 걸리는걸까...? 진짜 심오하게 생각해 볼 필요가 있다.'
global_x = 10
def myfunc1():
global global_x
global_x = 30
y = 20
print( global_x, y)
global_x=100
myfunc1()
print( global_x)
def myfunc2(name="홍길동", age=21, phone="010-0000-0001"):
print(name)
print(age)
print(phone)
myfunc2()
myfunc2("임꺽정", 33)
myfunc2(name="둘리")
myfunc2(age=23)
myfunc2(phone="8-4833")
print(range(1, 6))
for i in range(1,6):
print(i)
def myrange(start=1, end=5):
i=start
while i<=end:
yield i
i = i + 1
gen = myrange(end=1000)
print( next( gen ))
print( next( gen ))
print( next( gen ))
print( next( gen ))
print( next( gen ))
for i in myrange(1, 10):
print(i)
"""
1. 데이터가 너무 커서 한번에 생성할 수 없을때
2. 무한한 작업이 필요할때
3. 파일을 계속 읽어서 처리하고자 할때때
"""
함수활용
def circle():
radius = int(input("반지름을 입력하세요 : "))
circle_area = radius * radius * 3.14
print(f"\n원의 넓이는 {circle_area} 입니다.\n")
def square():
width = int(input("가로를 입력하세요 : "))
length = int(input("세로를 입력하세요 : "))
square_area = width * length
print(f"\n사각형의 넓이는 {square_area} 입니다.\n")
def trapezoid():
upper = int(input("윗변을 입력하세요 : "))
lower = int(input("아랫변을 입력하세요 : "))
height = int(input("높이를 입력하세요 : "))
trapezoid_area = (upper+lower) * height / 2
print(f"\n사다리꼴의 넓이는 {trapezoid_area} 입니다.\n")
def main():
while True:
print("1.원의 면적", end = "\t")
print("2.사각형 면적", end = "\t")
print("3.사다리꼴 면적", end = "\t")
print("0.종료")
choice = int(input("0~3 중 선택하세요 : "))
if choice == 1:
circle()
elif choice == 2:
square()
elif choice == 3:
trapezoid()
elif choice == 0:
print("프로그램을 종료합니다.")
return
else:
print("\n잘 고르자. 0~3 사이인데 그걸 못고르냐 친구야")
print("기회 함 더줄테니까 잘 적자잉\n")
def main2():
myfunctions = {"1":circle, "2":square, "3":trapezoid}
while True:
print("1.원의 면적", end = "\t")
print("2.사각형 면적", end = "\t")
print("3.사다리꼴 면적", end = "\t")
print("0.종료")
choice = (input("0~3 중 선택하세요 : "))
if choice in myfunctions.keys():
myfunctions[choice]()
else:
return print("프로그램을 종료합니다.")
def append():
list1 = []
while True:
s = input("입력하세요(중지하려면 '끝' 입력) : ")
if s == "끝":
break
list1.append(s)
return list1
def remove(list1):
removelist = list(set(list1))
return removelist
def main():
data = []
while True:
print("1. 리스트 입력")
print("2. 중복값 제거한 리스트 반환 ")
print("3. 종료")
sel = int(input("1 ~ 3중에 선택하세요 : "))
if sel == 1:
data = append()
print(f"\n원본데이터는 {data}입니다.\n")
elif sel == 2:
result = remove(data)
print(f"\n중복제거한 리스트는 {result}입니다.\n")
elif sel == 3:
return print("\n프로그램을 종료합니다.")
main()
def myint(s):
sum = 0
for c in s:
if ord(c) < ord("0") or ord(c) > ord("9"):
return -1
sum = sum * 10 + ord(c) - ord("0")
return sum
print(myint("123") + myint("345"))
def reverse():
sen = input("문장을 입력하세요 : ")
result = sen[::-1]
print(result)
reverse()
def reverse(s):
result = ""
for i in range(len(s)-1, -1, -1):
result += s[i]
return result
과제
가위바위보_객체지향(김성재풀이)
- 생각보다 과제를 빨리 끝냈다. 객체지향에 대해 이해는 못하지만 어느정도 구조는 이해가 된 상태이다. 생성자를 통해 변수를 만들고 그에 따른 입력/계산/출력의 구조로 코드를 작성했다. 점점 코드가 익숙해지고 있다.
import random
class ScissorsRockPaper:
def __init__(self):
self.choice = [1, 2, 3]
self.drawcount = 0
self.userwincount = 0
self.comwincount = 0
def com(self):
com_choice = random.randint(1,3)
return com_choice
def user(self):
while True:
user_choice = int(input("\n1.가위, 2.바위, 3.보 (숫자로 선택) : "))
if user_choice not in self.choice:
print("다시 입력하세요!!! " )
continue
else :
return user_choice
def whoisWinner(self, user_choice, com_choice):
if user_choice == com_choice:
result = 1
return result
elif (user_choice == 1 and com_choice == 3) or (user_choice == 2 and com_choice == 1) or (user_choice == 3 and com_choice == 2):
result = 2
return result
else:
result = 3
return result
def start(self):
print("게임을 시작합니다! 과연 승자는!! ")
def output(self):
self.start()
for i in range(0,10):
user_choice = self.user()
com_choice = self.com()
result = self.whoisWinner(user_choice, com_choice)
if result == 1:
print("무승부")
self.drawcount += 1
elif result == 2:
print("사람 승!")
self.userwincount += 1
else :
result == 3
print("컴퓨터 승 ㅠㅠ")
self.comwincount += 1
print("\n게임종료")
print(f"사람 승 : {self.userwincount}, 컴퓨터 승 : {self.comwincount}, 무승부 {self.drawcount}")
print(f"사람 승률 : {self.userwincount / 10:.2f}, 컴퓨터 승률 : {self.comwincount / 10:.2f}")
game1 = ScissorsRockPaper()
game1.output()
가위바위보_객체지향(백현숙강사님풀이)
코드를 입력하세요
복습

gpt를 이용한 유사예제
"숫자 맞추기 게임" 클래스 만들기
import random
class GuessNumber:
def __init__(self):
self.choice = range(1,101)
def com(self):
com_choice = random.randint(1,100)
return com_choice
def user(self):
while True:
user_choice = int(input("1~100사이 숫자를 하나 입력하세요 : "))
if user_choice not in self.choice:
print("다시 입력하세요. 1~100사이 숫자입니다. ")
else:
return user_choice
def compare(self, user_choice, com_choice):
while True:
if user_choice == com_choice:
return "정답입니다."
elif user_choice > com_choice:
return "Down!!"
else:
user_choice < com_choice
return "Up!!"
def start(self):
print("숫자 맞추기를 시작합니다! ")
def main(self):
self.start()
com_choice = self.com()
while True:
user_choice = self.user()
result = self.compare(user_choice, com_choice)
print(result)
if result == "정답입니다.":
break
g1 = GuessNumber()
g1. main()
"업다운 숫자 게임 with 제한된 기회" 클래스 만들기
import random
class UpDownGame:
def __init__(self):
self.choice = range(1,51)
def com(self):
com_choice = random.randint(1,50)
return com_choice
def user(self):
user_choice = int(input("1~50 사이의 숫자를 입력하세요 : "))
if user_choice not in self.choice:
return "다시 입력하세요. 1~50사이의 숫자입니다. "
else:
return user_choice
def compare(self, user_choice, com_choice):
while True:
if user_choice == com_choice:
return "정답"
elif user_choice > com_choice:
return "Down"
else:
return "Up"
def start(self):
print("업다운 숫자게임을 시작합니다. 기회는 총 7번!!")
def main(self):
self.start()
com_choice = self.com()
attempts = 7
while attempts > 0:
user_choice = self.user()
result = self.compare(user_choice, com_choice)
print(result)
attempts = attempts - 1
if result == "정답":
print(f"축하합니다. 정답은 {result}입니다.")
else:
print(f"틀렸습니다. 남은 기회는 {attempts}번 입니다.\n")
else:
print(f"주어진 기회를 전부 사용했습니다. 정답은 {com_choice}입니다ㅠㅠ ")
game1 = UpDownGame()
game1.main()