Python에서 조건문은 기본적으로 if와 else로 표현한다.
if 다음에 추가적인 조건을 더 작성할 경우 elif를 사용하면 된다.
들여쓰기
if를 사용할 때부터 들여쓰기(indentation)의 역할이 두드러진다.
if문에 종속되는 코드는 모두 tab을 눌러 들여쓰기 해야한다.
if 안에 또 if가 들어가 있다면 그 안에 들어가는 코드는 당연히 tab 두 번.
들여쓰기를 어떻게 하느냐에 따라 코드의 논리가 달라진다.
들여쓰기를 잘못해서 발생하는 에러가 많으므로 주의!
=과 ==의 차이
Python에서 '='는 변수 지정에 쓰이기 때문에 True, False 등 Boolean 논리를 사용할 때는 '=='를 사용한다.
예를 들어, a=3은 a라는 변수에 3이라는 숫자를 저장한다는 개념이고,
a==3은 'a는 3이다'라는 명제다. 즉, 참(True)과 거짓(False)을 구분할 때 사용된다.
조건문을 활용해 기초적인 CRUD(Create, Read, Update, Delete) 기능을 구현해봤다.
이름과 전화번호로 구성된 리스트를 추가, 검색, 수정, 삭제할 수 있다.
nameList = ["James", "Daniel", "John", "Adam", "Joshua"]
phoneList = ["017-2533-5455", "017-2789-4442", "017-2555-2444", "017-5333-4455", "017-1828-2888"]
menu = input("Add(a), Search(s), Edit(u), Delete(d): ")
if menu == 'a': # 이름과 전화번호를 공백 한 칸을 사이에 두고 입력
line = input('Type a name and phone number with a blank in between: ').split()
nameList.append(line[0].title())
phoneList.append(line[1])
print(f"\nSuccessfully added {line[0].title()}.")
print("\n***** Name List *****\n", nameList)
print("***** Phone List *****\n", phoneList)
elif menu == 's': # 인덱스 번호로 검색 or 이름으로 검색
s = input('Search by number(1), Search by name(2): ')
if s == '1':
num = input('Enter a number: ')
msg = f'{nameList[int(num)]}: {phoneList[int(num)]}'
print('\n***** Search Result *****')
print(msg)
elif s == '2':
name = input('Enter a name: ').title()
try:
idx = nameList.index(name)
except Exception as e: # 리스트에 없는 이름을 입력하면 오류 메시지 표시
print('Search Failed.', e)
msg = f'{name}: {phoneList[idx]}'
print('\n***** Search Result *****')
print(msg)
else:
print("Input Error")
elif menu == 'u': # 인덱스 번호 입력해 수정
num = input('Enter a number: ')
line = input('Type a new name and phone number with a blank in between: ').split()
nameList[int(num)] = line[0]
phoneList[int(num)] = line[1]
print("\nSuccess")
print("\n***** Name List *****\n", nameList)
print("***** Phone List *****\n", phoneList)
elif menu == 'd': # 인덱스 번호 입력해 삭제
d = input('Enter a number: ')
confirm = input(f"Are you sure want to delete {nameList[int(d)]}? (y/n) :") # 삭제 여부 재확인
if confirm == 'y':
print(f"\nSuccessfully deleted {nameList[int(d)]}.")
del nameList[int(d)]
del phoneList[int(d)]
print("\n***** Name List *****\n", nameList)
print("***** Phone List *****\n", phoneList)
elif confirm == 'n':
print(f"\n{nameList[int(d)]} not deleted.")
else:
print("Input Error")
else:
print("Input Error")
실행화면
Add(a), Search(s), Edit(u), Delete(d): s
Search by number(1), Search by name(2): 1
Enter a number: 4
***** Search Result *****
Joshua: 017-1828-2888
>>>
'Python Basic' 카테고리의 다른 글
try, except 블럭으로 에러 및 예외 처리 - Python(파이썬) (0) | 2020.11.13 |
---|---|
for Loop(반복문) 다양한 활용: range(), List, Tuple, 구구단 만들기- Python(파이썬) (0) | 2020.11.13 |
List(리스트) 생성, 추가, 수정, 삭제 list(), append(), remove(), pop() - Python(파이썬) 함수 (0) | 2020.11.05 |
List(리스트) 합계, 평균, 원소 개수 sum(), len() - Python(파이썬) 함수 (0) | 2020.11.05 |
List(리스트) 정렬 sorted(), sort() 차이 - Python(파이썬) 함수 (0) | 2020.11.05 |