리스트(lists)

리스트의 정의 및 선언

mbti = ['INFP', 'ENFP', 'ISTJ', 'ESTP']
print(mbti)
print(mbti[0])

 

파이썬에서 리스트는 타입을 통일하지 않아도 된다.

my_list = [123, 'apple']
print(my_list)

그러나 for 문이나 while 문 등에서 혼란을 야기할 수 있기 때문에 되도록 통일해주는 것이 좋다.

 

리스트 데이터 접근 및 조작

제거하는 함수의 종류는 비교적 많은 편이다.

colors = ['red', 'blue', 'green']

# 수정
colors[2] = 'black'
print(colors)

# 추가
colors.append('purple')
print(colors)

# 추가 2
colors.insert(1, 'yellow')
print(colors)

# 제거 1
del colors[0]
print(colors)

# 제거 2
color = colors.pop(0) # 인덱스 값을 넣지 않으면 끝부터 삭제
print(colors)
print(color)

# 제거 3
colors.remove('blue')
print(colors)

del 함수는 제거와 동시에 더이상 그 값을 사용할 수 없지만 pop() 함수는 제거한 값을 반환하여 다시 사용할 수 있다.

 

리스트 정렬

sort() 함수는 리스트를 오름차순으로 반환하며 reverse = True를 넣으면 내림차순으로 반환한다.

colors = ['blue', 'red', 'gray', 'black', 'yellow', 'orange']

# 정렬 1
colors.sort()
print(colors)

colors.sort(reverse = True)
print(colors)

# 정렬
print(sorted(colors))

 sort() 함수는 리스트를 오름차/내림차순으로 반환하지만 sorted() 함수는 리스트 자체를 정렬시킨다.

 

len() 함수는 리스트의 값의 개수를 반환한다.

print(len(colors))

 

인덱스 번호를 -1로 하면 리스트의 마지막 값을 반환한다.

print(colors[-1])

값이 존재하지 않는 인덱스 번호를 넣지 않도록 주의한다.

 

리스트 슬라이싱 및 복사

원하는 범위만큼 리스트의 범위를 취할 수 있는 방법

colors = ['blue', 'red', 'gray', 'black', 'yellow', 'orange']

print(colors[1:5])
print(colors[:4])
print(colors[2:])
print(colors[-5:])

 

새로운 리스트에 기존의 리스트를 반환 받아 사용할 수 있다.

colors = ['blue', 'red', 'gray', 'black', 'yellow', 'orange']
# colors_2 = colors
colors_2 = colors[:]

colors_2.pop()

print(colors)
print(colors_2)

기존 리스트가 변형될 수 있기 때문에 변수를 직접 가져와서 쓰지 않는 것이 좋다.

 

리스트와 흐름 제어

조건문과 반복문을 통한 리스트의 활용

scores = [88, 100, 96, 43, 65, 78]
scores.sort(reverse=True)

for score in scores:
    if score >= 80:
        print(score)
    else:
        print("Fail")

 

리스트 최댓값/최솟값/총합/평균

scores = [88, 100, 96, 43, 65, 78]

max_val = max(scores) # 최댓값
min_val = min(scores) # 최솟값
sum_val = sum(scores) # 총합
avg_val = sum(scores) / len(scores) # 평균

 

 

튜플(tuples)

튜플의 정의 및 특징

튜플은 전체를 새로 할당할 수는 있지만 요소의 값을 변경할 수 없다.

tup = (1, 20, 40)
print(tup[0])

#tup[0] = 100
tup = (100, 30, 4)
print(tup)

 

튜플/리스트 변환

tup = (1, 20, 40)

# 리스트 변환 1
list_1 = list(tup)
print(list_1)

# 리스트 변환 2
list_2 = [x for x in tup]
print(list_2)

# 리스트 변환 3
list_3 = []

for x in tup:
    list_3.append(x)
    
print(list_3)

 

 

딕셔너리

딕셔너리 정의 및 선언

딕셔너리는 키-값이 한 쌍이다.

student = {
    "student_no" : "202301234",
    "major" : "English",
    "grade" : 1
}

print(student["student_no"])

 

또한 키 값을 재할당 할 수 있다.

student = {
    "student_no" : "202301234",
    "major" : "English",
    "grade" : 1
}

student["student_no"] = "202301235"

print(student)
print(student["student_no"])

 

딕셔너리 데이터 조작

student = {
    "student_no" : "202301234",
    "major" : "English",
    "grade" : 1
}

# 추가
student["gpa"] = 4.5
print(student)

# 수정
student["gpa"] = 4.3
print(student)

# 삭제
del student["grade"]
print(student)

 

딕셔너리 함수

student = {
    "student_no" : "202301234",
    "major" : "English",
    "grade" : 1
}

# 데이터 접근
print(student.get("major"))
print(student.get("gpa", "해당 키-값 쌍이 없습니다."))

# 딕셔너리의 키를 반환
print(student.keys())

# 딕셔너리의 값을 반환
print(student.values())

키-값을 반환하는 함수를 리스트로 형변환하여 사용할 수 있다.

student = {
    "student_no" : "202301234",
    "major" : "English",
    "grade" : 1
}

print(list(student.keys()))
print(list(student.values()))

 

딕셔너리와 반복문

tech = {
    "HTML" : "Abvanced",
    "JavaScript" : "Intermediate",
    "Python" : "Expert",
    "Go" : "Novice"
}

for key in tech.keys():
    print(key)

for value in tech.values():
    print(value)

for key, value in tech.items():
    print(f'{key} - {value}')

 

중첩

# 중첩(Nesting)

student_1 = {
    "student_no" : "1",
    "gpa" : "4.3"
}

student_2 = {
    "student_no" : "2",
    "gpa" : "3.8"
}

students = [student_1, student_2]

for student in students:
    print(student['student_no']) # 공통되는 값

for student in students:
    student['graduated'] = False
    print(student) # 졸업여부 추가

 

하나의 키에 리스트로 여러 개의 값을 할당할 수 있다.

student = {
    "subjects" : ["회계원리", "중국어회화"]
}

print(student["subjects"])

subjects_list = student["subjects"]

for subject in subjects_list:
    print(subject)

 

딕셔너리 또한 값을 할당할 수 있다.

student = {
    "scholarship" : {
        "name" : "국가장학금",
        "amount" : "1000000"
    }
}

print(student)

for key in student.keys():
    print(key)

for value in student.values():
    for value_2 in value.values():
        print(value_2)

 

 

'Back-End > Python' 카테고리의 다른 글

회원가입 프로그램 실습 - 파이썬(Python) 편  (0) 2023.08.08
함수  (0) 2023.08.07
조건문과 반복문  (0) 2023.07.20
변수와 자료형  (0) 2023.07.19
파이썬 for Beginner 3판 14장 연습문제 답(더보기 클릭)  (0) 2023.07.13
조건문(conditional)

if else 문

if False:
     print("True")
else:
    print("False") # False

if 4 > 3:
    print("a") # a
else :
    print("b")

 

input은 입력값을 string으로 처리하기 때문에 정수나 실수 타입의 값을 받을 때에는 형변환 해주어야 한다.

value = input("값을 입력해주세요: ")

if int(value) > 10:
    print("a")
else:
    print("b")

 

if else 문

day = input("요일을 입력해주세요(0~6): ")

if day == "0":
    print("휴무")
elif day == "6":
    print("단축영업")
elif day == "1":
    print("연장영업")
else:
    print("정상영업")

 

 

반복문(loops)

for 문

i = 0
sum = 0

for i in range(1, 101):
    sum = sum + i

print(sum)

 

while 문

progress = 0

while progress < 100:
    
    progress = progress + 1
    print(f"{progress}% completed")

 

 

파이썬은 별도의 세미콜론( ; )이 필요없이 개행하면 소스가 새로 시작한다는 의미이다.

 

데이터를 반복적으로 활용하거나 원하는 형식으로 조절하기 위해서는 데이터를 공간에 넣어야한다. 그러기 위해서는 변수를 선언해야한다.

# greeting이라고 하는 변수 선언
# 이 변수에 문자열 값을 할당
greeting = "안녕하세요:)"
print(greeting)

# 변수는 데이터를 변경해서 할당할 수 있는 공간
greeting = "반갑습니다:)"
print(greeting)

 

파이썬에서의 변수의 특징

  • 변수 사이에 공백 허용되지 않음
  • 단어 사이는 _(언더스코어)를 사용하여 연결
  • 변수를 선언하기 위한 문자열은 숫자/특수문자로 시작이 불가
  • 예약어 사용 불가
  • 가급적 소문자 사용
  • 오타 주의

 

문자열(Strings)

문자의 나열

 

대소문자 변환

city = "seoul" # Seoul, SEOUL, SEOul
print(city)

# 대문자
city.upper()
print(city.upper())

city = city.upper()
print(city)

# 소문자
city.lower()
print(city.lower())

city = city.lower()
print(city)

 

공백 제거

occupation = "   developer   "
print(occupation)

# 우측 공백 제거
occupation.rsplit()
print(occupation.rsplit())

# 좌측 공백 제거
occupation.lstrip()
print(occupation.lsplit())

# 양옆 공백 제거
occupation.strip()
print(occupation.split())

 

개행 및 공백

print("INFP\nENFP\nISTJ\nESTJ")
print("INFP\tENFP\tISTJ\tESTJ")

 

시작과 끝 제거

# 시작 제거
score = "점수:90"
print(score.removeprefix("점수:"))

# 끝 제거
score_2 = "75점"
print(score_2.removesuffix("점"))

 

수정

city = "서울 중구"
print(city.replace("서울", "서울시"))

 

f-string

si_1 = "용인"
gu_1 = "기흥"
address_1 = f"{si_1}시 {gu_1}구"
print(address_1)

si_2 = "서울"
gu_2 = "종로"

# 서울시 종로구
# 용인시 기흥구
# (시의 이름)시 (구의 이름)구
print(f"{si_1}시 {gu_1}구")
print(f"{si_2}시 {gu_2}구")

 

 

숫자(numbers)

 

정수의 계산

a = 2
b = 3

print(a + b) # 더하기
print(a - b) # 빼기
print(a * b) # 곱하기
print(a / b) # 나누기

print(a ** b) # 제곱

print(a + b * b)
print((a + b) * b) # 괄호

print(a // b) # 몫
print(a % b) # 나머지

 

실수(Float)의 계산

실수와 연산하는 수는 그 결과가 모두 실수이다.

x = 10.0
y = 0.3
z = 1

print(x - y)
print(x + y)
print(x * y)
print(x / y)

print(x + z)
print(x - z)
print(x * z)
print(x / z)

 

숫자 표현

# 언더스코어(_)
price = 12_349_000_000_000
print(price)

 

상수(contants)

상수로 선언된 변수는 재할당 되어서는 안된다.

PI = 3.141592

 

문자열 - 숫자 간의 변환

a = 100
b = "100"
c = "0.453"

a = str(a) # 문자열
b = int(b) # 숫자
c = float(c) # 실수

 

 

논리형(Bool, Boolean)

다른 언어들과 달리 파이썬에서는 불 값이 대문자로 시작한다.

print(3 > 2) # True
print(3 == 3) # True
print(3 == 3.0) # True
print(3 is 3.0) # False

 

 

명령 프롬프트

CLI에 텍스트를 입출력하는 방법

input("설치를 계속 진행하시겠습니까? (y/n): ")

text = input("출력할 텍스트를 입력해주세요: ")
print(text)

 

 

 

주석

주석을 사용하는 이유

  • 테스트를 위해 코드를 임시로 무효화 하기 위해서
  • 함수, 변수 등의 의미를 다른 개발자들과 협업을 위해 공유하기 위해서
  • 프로그램을 유지보수하고 체계적인 프로젝트 관리를 위해서

 

주석 사용법

# 한 줄 주석입니다.

"""
여러 줄 주석입니다.
여러 줄 주석입니다.
여러 줄 주석입니다.
"""

'''
여러 줄 주석입니다.
print{"test"}
'''

 

 

연습문제

1. 다음은 외부 라이브러리인 pygame을 파이썬에서 추가하기 위한 명령입니다. 옳은 것을 고르세요.

① pip install pygame

② pip upgrade pygame

③ pip setup pygame

pip download pygame

 

더보기

답 : 1

 

2. 다음 각 설명에 필요한 Pillow 함수를 쓰세요.

(1) 이미지 회전

(2) 이미지 밝게/어둡게

(3) 이미지 블러링/엠보싱

(4) 이미지 복사

(5) 이미지 확대/축소

(6) 이미지 좌우/상하 반전

 

더보기

답 : (1) rotate(각도)

(2) ImageEnhance.Brightness(이미지).enhance(밝기 값)

(3) filter(ImageFilter.BLUR) , filter(ImageFilter.EMBOSS)

(4) copy()

(5) resize((폭, 높이))

(6) transpose() 

 

3. [프로그램 2]를 다음과 같이 기능을 추가하거나 변경해 보세요.

    · 우주괴물이 화면의 위에서 아래로 지그재그로 내려오도록 하자. 또한 게임의 박진감을 위해서 우주괴물의 속도가 5~9가 되도록 조절하자.

    · 우주괴물을 맞힐 때마다 우주선의 그림이 다른 우주선으로 변경되도록 하자.

    · 우주괴물이 살아서 오른쪽 끝까지 도달하면 점수에서 1점을 빼자. 즉, 점수는 마이너스 점수도 나올 수 있다.

    · 만약, 우주선과 우주괴물이 부딪히면 5초간 화면을 멈추고, 게임 종료 메시지를 화면에 출력하자. 그리고 프로그램을 종료한다.

* 다른건 다 했는데 지그재그로 내려오게 하는걸 모르겠네요ㅠㅠ 아는 분 댓글 부탁드립니다

더보기

답 :

import pygame
import random
import sys


## 함수 선언 부분 ##
# @기능 2-5 : 매개변수로 받은 객체를 화면에 그리는 함수를 선언한다.
def paintEntity(entity, x, y) : 
   monitor.blit(entity, (int(x), int(y)))

# @기능 5-4 : 점수를 화면에 쓰는 함수를 선언한다.
def writeScore(score) :
    myfont = pygame.font.Font('NanumGothic.ttf', 20)      # 한글 폰트
    txt = myfont.render(u'파괴한 우주괴물 수 : ' + str(score), True, (255-r, 255-g, 255-b))
    monitor.blit(txt, (10, sheight - 40))
    
def writeMessage(text) :
    myfont = pygame.font.Font('NanumGothic.ttf', 50)      # 한글 폰트
    text = myfont.render(text, True, (255-r, 255-g, 255-b))
    monitor.blit(text, (swidth/2-200, sheight/2-30))

def crash() :
    writeMessage('우주선 폭파!! 게임 끝!')
    pygame.display.update()
    pygame.time.delay(5000)
    pygame.quit()
    sys.exit()

def playGame() :
    global monitor, ship, monster, missile 

    r = random.randrange(0, 256)
    g = random.randrange(0, 256)
    b = random.randrange(0, 256) 
    
     # @기능 2-2 : 우주선의 초기 위치 키보드를 눌렀을 때 이동량을 저장할 변수를 선언한다.
    shipX = swidth / 2  # 우주선 위치
    shipY = sheight * 0.8
    dx, dy = 0, 0  # 키보드를 누를때 우주선의 이동량
    
    # @기능 3-2 : 우주괴물을 랜덤하게 추출하고 크기와 위치를 설정한다.
    monster = pygame.image.load(random.choice(monsterImage))
    monsterSize = monster.get_rect().size                 # 우주괴물 크기
    monsterX = 0 
    monsterY = random.randrange(0, int(swidth * 0.3)) # 상위 30% 위치까지만
    monsterSpeed = random.randrange(5, 9)
    
    # 우주선을 랜덤하게 추출한다
    ship = pygame.image.load(random.choice(shipImage))
    shipSize = ship.get_rect().size

    # @기능 4-2 : 미사일 좌표를 초기화한다.
    missileX, missileY = None, None  # None은 미사일을 쏘지 않았다는 의미이다.

    # @기능 5-1 : 맞힌 우주괴물 숫자를 저장할 변수를 선언한다.
    fireCount = 0

    # 무한 반복
    while True :
        (pygame.time.Clock()).tick(50)  # 게임 진행을 늦춘다(10~100 정도가 적당)
        monitor.fill((r, g, b))              # 화면 배경을 칠한다.

        # 키보드나 마우스 이벤트가 들어오는지 체크한다.
        for e in pygame.event.get() :
            if e.type in [pygame.QUIT]  :
                pygame.quit()
                sys.exit()

            # @기능 2-3 : 방향키에 따라 우주선이 움직이게 한다.
            # 방향키를 누르면 우주선이 이동한다(누르고 있으면 계속 이동).
            if e.type in [pygame.KEYDOWN] :
                if e.key == pygame.K_LEFT : dx = -5
                elif e.key == pygame.K_RIGHT : dx = +5
                elif e.key == pygame.K_UP : dy = -5
                elif e.key == pygame.K_DOWN : dy = +5
                # @기능 4-3 : 스페이스바를 누르면 미사일을 발사한다.
                elif e.key == pygame.K_SPACE : 
                    if missileX == None :                     # 미사일을 쏜 적이 없다면
                        missileX = shipX + shipSize[0]/2    # 우주선 위치에서 미사일을 발사한다.
                        missileY = shipY

            # 방향키를 떼면 우주선이 멈춘다.
            if e.type in [pygame.KEYUP] :
                 if e.key == pygame.K_LEFT or e.key == pygame.K_RIGHT \
                    or e.key == pygame.K_UP or e.key == pygame.K_DOWN : dx, dy = 0, 0

        # @기능 2-4 : 우주선이 화면 안에서만 움직이게 한다.
        if (0 < shipX+dx and shipX+dx <= swidth-shipSize[0]) \
            and (sheight/2 < shipY+dy and shipY+dy <= sheight - shipSize[1]) :  # 화면의 중앙까지만
            shipX += dx
            shipY += dy
        paintEntity(ship, shipX, shipY)   # 우주선을 화면에 표시한다.

        # @기능 3-3 : 우주괴물이 자동으로 나타나 왼쪽에서 오른쪽으로 움직인다.
        monsterX += monsterSpeed
        monsterY += monsterSpeed
        if monsterY > sheight :
            monsterX = random.randrange(0, int(swidth * 0.3))
            monsterY = 0
            # 우주괴물 이미지를 무작위로 선택한다.
            monster = pygame.image.load(random.choice(monsterImage))
            monsterSize = monster.get_rect().size
            monsterSpeed = random.randrange(5, 9)
           
        paintEntity(monster, monsterX, monsterY)
        
        # 놓치면 점수 빼기
        if monsterY >= sheight:
            fireCount -= 1
        
        # @기능 4-4 : 미사일을 화면에 표시한다.
        if missileX != None :                          # 총알을 쏘면 좌표를 위로 변경한다.
            missileY -= 10
            if missileY < 0 :
                  missileX, missileY= None, None   # 총알이 사라진다.
        if missileX != None :           # 미사일을 쏜 적이 있으면 미사일을 그려준다.
            paintEntity(missile, missileX, missileY)
            # @기능 5-2 : 우주괴물이 미사일에 맞았는지 체크한다.
            if (monsterX < missileX and missileX < monsterX + monsterSize[0]) and \
                   (monsterY < missileY and missileY < monsterY + monsterSize[1]) :
                fireCount += 1

                # 우주괴물을 초기화(무작위 이미지로 다시 준비)
                monster = pygame.image.load(random.choice(monsterImage))
                monsterSize = monster.get_rect().size
                monsterX = 0
                monsterY =random.randrange(0, int(swidth * 0.3))
                monsterSpeed = random.randrange(1, 5)
                
                # 미사일을 초기화한다.
                missileX, missileY= None, None   # 총알이 사라진다.

        # @기능 5-3 : 점수를 화면에 쓰는 함수를 호출한다.
        writeScore(fireCount)
        
        # 화면을 업데이트한다.
        pygame.display.update()
        
        # 우주선이 우주괴물과 충돌했는지 체크
        if (shipX < monsterX and monsterX < shipX + shipSize[0]) and \
              (shipY < monsterY and monsterY < shipY + shipSize[1]) :
           crash()

        
## 전역 변수 선언 부분 ##
r, g, b = [0] * 3                # 게임 배경색
swidth, sheight = 500, 700  # 화면 크기
monitor = None               # 게임 화면
ship, shipSize = None, 0     # 우주선의 객체와 크기 변수

# @기능 3-1 : 랜덤하게 사용할 우주괴물의 이미지 10개를 준비한다.
monsterImage = ['monster01.png', 'monster02.png', 'monster03.png', 'monster04.png', \
                'monster05.png', 'monster06.png', 'monster07.png', 'monster08.png', \
                'monster09.png', 'monster10.png']
monster = None   # 우주괴물

missile = None     # 미사일


## 메인 코드 부분 ##
pygame.init()
monitor = pygame.display.set_mode((swidth, sheight))
pygame.display.set_caption('우주괴물 무찌르기')

# @기능 2-1 : 우주선 이미지를 준비하고 크기를 구한다.
ship = pygame.image.load('ship02.png')
shipSize = ship.get_rect().size

# @기능 4-1 : 미사일 이미지를 추가한다.
missile = pygame.image.load('missile.png')

playGame()

 

 

*주의사항 : 제가 직접 푼 것이므로 틀린 부분이 있을 수 있습니다. 오타나 틀린 부분 지적 환영!

+ Recent posts