python 조건문 (if, while, for)

조건문

  • 특정 조건에 따라서 코드를 실행하고자 할 때 사용
  • if, else, elif
    1
    2
    3
    4
    5
    6
    # if 문이 ture일 때 구문 안의 결과가 실행됨
    if True:
    print("python")

    print("done")
    # python done
    1
    2
    3
    4
    5
    6
    # if 문이 false일 때 구문 이외의 결과가 실행됨
    if False:
    print("python")

    print("done")
    # done
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    # 조건부문 : bool 데이터 타입 이외의 데이터 타입이 오면 bool으로 형변환 되어 판단
    # int : 0을 제외한 나머지 값은 True
    num = 0
    if num:
    print("python_1")
    # 출력값 없음

    num = 1
    if num:
    print("python_2")

    # python_2
    1
    2
    3
    4
    5
    number = 7
    if number % 2:
    print('홀수')
    else:
    print('짝수')
    1
    2
    3
    # float : 0.0을 제외한 나머지 실수는 True
    # str : ""을 제외한 나머지 문자열은 True
    # list, tuple, dict : [], (), {}를 제외한 나머지는 True
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    # 지갑에 돈이 10000원 이상 있으면 택시를 탑니다. 
    # 2000원 이상이 있으면 버스를 탑니다.
    # 그렇지 않으면 걸어서 집에 갑니다.
    money = 5000
    if money >= 10000:
    print('택시를 타고 집에 갑니다.')
    elif money >= 5000:
    print('광역버스를 타고 집에 갑니다.')
    elif money >= 2000:
    print('일반버스를 타고 집에 갑니다.')
    else:
    print("걸어서 집에 갑니다.")
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    # 계좌에 10000원이 들어있습니다. 
    # 인출 금액을 입력 받습니다.
    # 인출 금액이 계좌에 있는 금액보다 크면 "인출이 불가능합니다." 출력
    # 인출 금액이 계좌에 있는 금액보다 작으면 "인출 되었습니다." 출력
    # 마지막에 현재 계좌의 잔액을 출력
    account = 10000
    draw_money = int(input("인출 금액을 입력하세요. : "))
    if account >= draw_money:
    account -= draw_money
    print(str(draw_money) + "원이 인출되었습니다.")
    else:
    print("인출이 불가능합니다. " + str(draw_money - account) + "원의 잔액이 부족합니다.")

    print("현재 잔액은 " + str(account) + "원 입니다.")

삼항연산자

  • 간단한 if, else 구문을 한줄의 코드로 표현할 수 있는 방법
  • (True) if (condition) else (False)
    1
    2
    3
    4
    5
    6
    # data 변수에 0이면 "zero"출력, 아니면 "not zero"출력
    data = 0
    if data:
    print("not zero")
    else:
    print("zero")
    1
    2
    data = 1
    "not zero" if data else "zero"

반복문

  • 반복되는 코드를 실행할 때 사용
  • while, for, break, continue
  • list comprehention
    1
    2
    3
    4
    5
    6
    7
    8
    # while
    data = 3

    while data: # 조건이 False가 될 때까지 구문의 코드를 실행

    # 반복되는 코드
    print(data)
    data -= 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 학생이 국어: 80점, 영어: 90점, 수학: 100점 while 문을 이용해서 총점과 평균을 출력
# 학생의 점수는 list, dict 표현
# len(), dict.values(), list.pop()
# list
subject = ["korean", "english", "math"]
score = [80, 90, 100]
total, avg = 0, 0

while True:
total = sum(score)
avg= total / len(score)
print('3과목 총점은 ' + str(total) + '점 입니다.' )
print('3과목 평균 점수는 {}점 입니다. '.format(avg))
break
1
2
3
4
5
6
7
8
9
10
points_dict = {"korean": 80, "english": 90, "math": 100}
total, avg = 0, 0

while True:
total = sum(points_dict.values())
avg = total / len(subject)

print("3과목 총점 : ", total)
print("3과목 평균 : ", avg)
break
1
2
3
4
5
6
7
8
9
10
11
12
subjects_ls = ["korean", "english", "math"]
points_ls = [80, 90, 100]
points_dict = {"korean": 80, "english": 90, "math": 100}

datas = points_ls.copy() # 깊은 복사 : 원본 데이터를 보존

total, avg = 0, 0

while datas:
total += datas.pop()
avg = total / len(points_ls)
total, avg

무한루프

1
2
3
4
result = 1
while result:
result += 1
print(result)
  • break : 반복문을 중단 시킬 때 사용되는 예약어
    1
    2
    3
    4
    5
    6
    7
    8
    result = 1
    while result:

    if result >= 10:
    break

    result += 1
    print(result)

for

  • iterable한 데이터를 하나씩 꺼내서 value에 대입시킨 후 코드를 iterable변수의 값 갯수만큼 실행
    1
    2
    for <variable> in <iterables>:
    <code>
    1
    2
    3
    ls = [0, 1, 2, 3, 4]
    for data in ls:
    print(data)
    1
    2
    3
    4
    5
    6
    7
    8
    # continue: 조건부분으로 올라가서 콜드가 실행
    ls = [0, 1, 2, 3, 4]
    for data in ls:
    if data % 2: # data가 홀수가 되면 continue를 실행하여 다시 포문으로 돌아감
    continue

    # data가 짝수이면 print를 실행
    print(data, end=" ")

for를 이용해서 코드를 100번 실행

  • range 함수
    1
    2
    3
    4
    5
    list(range(100))
    result = 0
    for data in range(100):
    result += data
    result
  • offset index 개념과 비슷하게 사용
    1
    list(range(5)), list(range(5, 10)), list(range(0, 10, 2))
    1
    2
    3
    4
    5
    # 0~10 까지 짝수를 더한 총합
    result = 0
    for number in range(0, 11, 2):
    result += number
    result
    1
    2
    3
    points_dict = {"korean": 80, "english": 90, "math": 100}
    for data in points_dict:
    print(data)

items 함수 사용

1
2
3
4
# dict 형태
points_dict = {"korean": 80, "english": 90, "math": 100}
for subject, point in points_dict.items():
print(subject, point)

zip 함수 사용

1
2
3
4
5
6
# list 형태
# for 문에서 iterable 데이터가 tuple로 나오면 여러개의 변수로 받을 수 있습니다.
subjects_ls = ["korean", "english", "math"]
points_ls = [80, 90, 100]
for subject, point in zip(subjects_ls, points_ls):
print(subject, point)

구구단 가로 출력

  • 21=2 31=3 … 9*1=9
  • 29=18 39=27 … 9*9=81
    1
    2
    3
    4
    5
    for i in range(1, 10): # 1, 2, 3, ... 9를 만들어 줌
    # print(i)
    for j in range(2, 10): # 2단, 3단, ... 9단을 만들어줌
    print('{}*{}={}'.format(j, i, i*j), end='\t')
    print()

List Comprehention

  • 리스트 데이터를 만들어주는 방법
  • for문 보다 빠르게 동작합니다.
1
2
3
4
5
6
7
# 각각 값에 제곱한 결과 출력
ls = [0, 1, 2, 3]
result = []

for data in ls:
result.append(data ** 2)
result
1
2
result = [data**2 for data in ls] # [연산 for 각각의 데이터 in 데이터의 집합]
result
1
2
3
4
5
# 리스트 컴프리헨션을 써서 홀수와 짝수를 리스트로 출력해주는 코드
# 삼항연산자 사용
ls = range(0, 11)
result = ["홀수" if data % 2 else "짝수" for data in ls]
result

리스트 컴프리헨션 조건문

  • 0 ~ 9까지에서 홀수만 출력하기
    1
    2
    ls = range(10)
    [i for i in ls if i%2]
    1
    2
    3
    4
    # dir(ls)에서 "__" 없는 함수만 출력하기
    ls = [1, 2, 3]
    dir(ls)
    [i for i in dir(ls) if i[:2] != '__'] # 앞에 2개가 __ 인 것을 제외
    1
    2
    3
    4
    # 앞글자가 c인 것만 가져오기
    ls = [1, 2, 3]
    dir(ls)
    [i for i in dir(ls) if i[:2] != '__' if i[:1] == 'c']
    1
    2
    3
    ls = [1, 2, 3]
    dir(ls)
    [i for i in dir(ls) if i[:2] != '__' and i[0] == 'c']

for문과 list comprehention 성능 비교

1
2
3
4
5
%%timeit # magic command : 셀 안에서 실행되는 시간 측정
ls = []
for num in range(1, 10001):
ls.append(ls)
len(ls)
1
2
3
%%timeit # magic command : 셀 안에서 실행되는 시간 측정
ls = [num for num in range(1, 10001)]
len(ls)
1
2
3
4
5
6
7
# 3의 배수만 찾기 소요시간 비교
%%timeit # magic command : 셀 안에서 실행되는 시간 측정
ls = []
for num in range(1, 10001):
if num % 3 == 0:
ls.append(num)
len(ls)
1
2
3
%%timeit # magic command : 셀 안에서 실행되는 시간 측정
ls = [num for num in range(1, 10001) if num % 3 == 0]
len(ls)