
a = None
if a is None:
print("a is None!")
else:
print("a is not None!")
# 출력 : a is None!
import copy
lst = [["멋쟁이", "호랑이처럼"], 2025, 1, 13]
shallow_lst = list(lst)
shallow_lst2 = copy.copy(lst)
deep_lst = copy.deepcopy(lst)
lst[0][1] = "사자처럼"
print(lst) # [['멋쟁이', '사자처럼'], 2025, 1, 13]
print(shallow_lst) # [['멋쟁이', '사자처럼'], 2025, 1, 13]
print(shallow_lst2) # [['멋쟁이', '사자처럼'], 2025, 1, 13]
print(deep_lst) # [['멋쟁이', '호랑이처럼'], 2025, 1, 13]
깊은 복사를 한 deepcopy의 결과는 원본 그대로였지만
얕은 복사를 한 나머지의 결과는 원본이 바뀌면 같이 바뀌었다.
import copy #deepcopy 함수 호출 위해서 copy 모듈 import
john = ['John', ('man','USA'),[175,23]]
tom = list(john) # 얕은 복사 = 껍데기만 새로 생성
chulsu = copy.copy(john) # 얕은복사
john[2][1] +=1
print(john)
print(tom)
print(chulsu)
import copy #deepcopy 함수 호출 위해서 copy 모듈 import
john = ['John', ('man','USA'),[175,23]]
tom = list(john) # 얕은 복사 = 껍데기만 새로 생성
chulsu = copy.deepcopy(john) # 깊은복사
john[2][1] +=1
print(john)
print(tom)
print(chulsu)
copy.copy에서 copy.deepcopy로 바꾸면 깊은 복사가 된다.
리스트를 간단하고 효율적으로 생성할 수 있는 Python의 문법으로
기존 for문을 사용하는 것보다 코드가 짧고 가독성이 좋다.
(하지만 난 기존에 for문을 쓰는 게 길이는 더 길지만 가독성은 더 좋은 것 같다.)
gugudan = [f"{i} * {j} = {i*j}" for i in range(2,10) for j in range(1, 10)]
for line in gugudan :
print(line)
even_num = [x for x in range (1, 101) if x % 2 == 0]
print(even_num)
multiples35 = [x for x in range(1, 101) if x % 3 == 0 or x % 5 == 0]
print(multiples35)
power_num = [x**2 for x in range(1, 11)]
print(power_num)
import random
class Lotto :
def __init__(self) :
self.lotto_set = None
def run(self) :
self.lotto_set = set()
while len(self.lotto_set) < 6 :
self.lotto_num = random.randint(1,45)
self.lotto_set.add(self.lotto_num)
print(self.lotto_set)
lotto = Lotto()
lotto.run()

# 갬블링 게임을 만들어보자.
# 두 사람이 게임을 진행한다.
# 이들의 이름을 키보드로 입력받으며 각 사람은 Person 클래스로 작성하라.
# 그러므로 프로그램에는 2개의 Person 객체가 생성되어야 한다.
# 두 사람은 번갈아 가면서 게임을 진행하는데
# 각 사람이 자기 차례에서 <Enter> 키를 입력하면, 3개의 난수가 발생되고
# 이 숫자가 모두 같으면 승자가 되고 게임이 끝난다.
# 난수의 범위를 너무 크게 잡으면 3개의 숫자가 일치하게 나올 가능성이 적기 때문에
# 숫자의 범위는 1~3까지로 한다.
import random
class Person : # 각 플레이어 객체를 생성하여 이름, 난수 리스트, 승리 여부를 저장함.
def __init__(self, name) :
self.name = name
self.rand_list = []
self.win = False
def rand_play(self) : # 1~3 난수 3개 저장
self.rand_list = [random.randint(1, 3) for i in range(3)]
def run (self) : #엔터 입력 시 난수 3개를 출력하고, 모두 같으면 win = True
self.win = None
print(f"[{self.name}]")
while True :
self.blank = input("<Enter> ")
if self.blank == "" :
break
else :
print("엔터만 눌러주세요.")
self.rand_play()
if len(set(self.rand_list)) == 1 : # 숫자 세 개가 같을 경우
print(f"{self.rand_list[0]}\t{self.rand_list[1]}\t{self.rand_list[2]}\t{self.name}님이 이겼습니다!")
self.win = True
else : # 그렇지 않을 경우
print(f"{self.rand_list[0]}\t{self.rand_list[1]}\t{self.rand_list[2]}\t아쉽군요!")
first_user = input("1번째 선수 이름 >> ")
second_user = input("2번째 선수 이름 >> ")
person1 = Person(first_user)
person2 = Person(second_user)
while True :
person1.run()
if person1.win :
break
person2.run()
if person2.win :
break
== : 값이 같은지를 비교하는 연산자로 같으면 True
id : 메모리 주소를 확인하여 주소가 같으면 True
is : id(a) == id(b)와 동일 (객체 동일성 비교)
4시부터 12 시 사이이면 => 굿모닝출력
12시부터 18 시 =>굿애프터눈 출력
18시부터 22 시 = > 굿 이브닝 출력
22시부터 04 시 => 굿나잇 출력
# datetime 모듈을 사용해서 현재 시간을 화면에 출력해보세요.
import datetime
now = datetime.datetime.now()
print(now) # 출력 : 2025-01-13 17:28:40.949667
# datetime 모듈의 now 함수의 리턴 값의 타입을 화면에 출력해보세요.
import datetime
now = datetime.datetime.now()
print(now) # 출력 : 2025-01-13 17:28:40.949667
print(type(now)) # 출력 : <class 'datetime.datetime'>
# datetime 모듈의 timedelta를 사용해서
# 오늘로부터 5일, 4일, 3일, 2일, 1일 전의 날짜를 화면에 출력해보세요.
import datetime
now = datetime.datetime.date(datetime.datetime.now())
for i in range(5, 0, -1) :
print(now + datetime.timedelta(i))
# 현재시간을 얻어온 후 다음과 같은 포맷으로 시간을 출력해보세요.
# strftime 메서드를 사용하세요.
from datetime import datetime
now = datetime.now()
formatted = now.strftime("%Y - %m - %d \t %H : %M : %S")
print(formatted) # 출력 : 2025 - 01 - 13 17 : 37 : 59
formatted = now.strftime("%H : %M : %S \t %Y - %m - %d")
print(formatted) # 출력 : 17 : 37 : 59 2025 - 01 - 13
# time 모듈, datetime 모듈을 사용해서
# 1초에 한 번 현재 시간을 출력하는 코드를 작성하세요.
from datetime import datetime
import time
while True :
now = datetime.now() # 현재 시간 정해진 포맷으로 알려줌
print(now.strftime("%Y - %m - %d \t %H : %M : %S"))
time.sleep(1) # 1초 대기
# 출력 :
2025 - 01 - 13 17 : 42 : 42
2025 - 01 - 13 17 : 42 : 43
2025 - 01 - 13 17 : 42 : 44
2025 - 01 - 13 17 : 42 : 45
2025 - 01 - 13 17 : 42 : 46
세줄요약 :
1. id 는 주소 == 값 비교 이다
2. 얕은 복사는 껍데기 복사 , 깊은복사는 안에꺼 까지.
3. set 은 중복불가, 순서 없음 이다.
리스트 컴프리헨션을 써보고 싶어서 갬블링 예제에서 슬쩍 써봤다.
이게 될까 싶어서 코드창 새로 열어서 저부분만 몇 번 돌려봤다.ㅋㅋㅋ
