파이썬 챌린지 4일차 TIL

seoyeon·2023년 3월 9일
0

UDR

목록 보기
4/42

딕셔너리

  • 여러값을 저장
  • 예) print(wintable['가위'])는 가위에 매칭되는 값 '보'를 출력 값으로 가짐

[list와의 차이점]

  • 새로운 값을 추가할 때
    ▷ list : append 함수 사용, 없는 자릿수에 값 추가 불가능
    ▷ dictionary : 딕셔너리 변경때와 같이 key값과 그에 대응하는 값 입력
  • 순서가 중요하지 않음 : 값 출력 시 순서 무작위
  • keys / values / items

📝 dict_basic

# 가위바위보 승패 판정
wintable = {
    '가위' : '보',
    '바위' : '가위',
    '보' : '바위'
}
print(wintable['가위'])

'''
words = ['a', 'b', 'c']
print(words[1])
'''

def rsp(mine, yours):
    if mine == yours:
        return 'draw'
    elif wintable[mine] == yours:
        return 'win'
    else:
        return 'lose'

result = rsp('가위', '바위')

messages = {
    'win' : '이겼다!',
    'draw' : '비겼네',
    'lose' : '졌어 ...'
}

print(messages[result])

📝 dictonary_edit

list = [1, 2, 3, 4, 5]
list[2] = 33
# list[5] = 6  / 오류 발생
list.append(6)

dict = { 'one' : 1, 'two' : 2 }
dict['one'] = 11
dict['three'] = 3

del(dict['one']) # 딕셔너리 삭제
list.pop(0) # 지우는 값 반환
dict.pop('two') # list와 동일

📝 dict_roof

seasons = ['봄', '여름', '가을', '겨울']
for season in seasons:
    print(season)

ages = {'Tod':35, 'Jane':23, 'Paul':62}

#key값 출력
for key in ages.keys():
    print(key)

#value값 출력
for value in ages.values():
    print(value)

for key in ages.keys():
    print('{}의 나이는 {}입니다.'.format(key, ages[key]))

for key, value in ages.items():
    print('{}의 나이는 {}입니다.'.format(key, value))

튜플

[list와의 차이점]

  • 순서가 정해진 값의 집합, 값 수정 가능 ↔ 값 수정, 삭제 불가
  • 리스트 : 대괄호 / 딕셔너리 : 중괄호 / 튜플 : 괄호

📝 예제 코드

list1 = [1, 2, 3]
tuple3 = tuple(list1)

While

  • if, for와 같은 반복문
  • 사용이유? 상황에 따라 더 간단하게 코딩을 할 수 있기 때문 → 상황에 따른 선택 필요

📝 예제 코드

selected = None
while selected not in ['가위', '바위', '보']:
    selected = input("가위, 바위, 보 중에 선택하세요 >")

print("선택된 값은: ", selected)

selected = None
if selected not in ['가위', '바위', '보']:
    selected = input("가위, 바위, 보 중에 선택하세요 >")

print("선택된 값은: ", selected)

#for
patterns = ['가위', '보', '보']
for pattern in pattern:
    print(patterns)

#while
length = len(patterns)
i=0
while i < length:
    print(patterns[i])
    i = i+1

break / continue

  • break : 반복문 종료
  • continue : 너무 깊게 들어가지 않게 하기 위함

📝 break_continue

list = [1, 2, 3, 4, 5, 7, 2, 5, 237, 55]
for val in list:
    if val % 3 == 0:
        print(val)
        break

for i in range(10):
    if i%2 !=0:
        print(i)
        print(i)
        print(i)
        print(i)

for i in range(10):
    if i%2 !=0:
        continue
    print(i)
    print(i)
    print(i)
    print(i)

try / except

  • try : 에러 발생 가능성 있는 코드,
  • except : 에러 발생 시 실행할 코드
  • 오류가 발생하는 경우 : 빈 값 불러오기, 타입이 맞지 않는 경우
  • 에러가 발생 시 실행 코드를 미리 지정

📝 try_except

text = '100%'
try:
    number = int(text)
except ValueError:
    print('{}는 숫자가 아니네요.'.format(text))

# list와 index를 받아들여 index에 해당하는 값을 출력 후 삭제하는 코드
# try, except
def safe_pop_print(list, index):
    try:
        print(list.pop(index))
    except IndexError:
        print('{} index의 값을 가져올 수 없습니다.'.format(index))

safe_pop_print([1, 2, 3], 5)

# if else
def safe_pop_print(list, index):
    if index < len(list):
        print(list.pop(index))
    else:
        print('{} index의 값을 가져올 수 없습니다.'.format(index))

safe_pop_print([1, 2, 3], 5)

#try, except 구문이 반드시 필요한 경우
try:
    import my_module
except ImportError:
    print("모듈이 없습니다.")

📸 강의 수강목록 캡처




profile
안녕하세용

0개의 댓글

관련 채용 정보