파이썬

02-2.조건문과 반복문

바꾸자키 2023. 8. 27. 18:53

1. 조건문

- 특정 조건에 따라서 코드를 실행하고자 할때 사용
* if
* else
* elif
* 삼항연산자

1-1. if

- 특정 조건에 따라서 코드를 실행시키고 싶을 때 사용

if <condition>:
    <code_1>
state = True
if state:
    print("if")
print("done")

->if
done

state = False
if state:
    print("if")
print("done")

->done

money = 10000
if money >= 30000:
  print('고기를 산다')
if money <= 30000:
  print('고기를 못 산다')

->고기를 못 산다


1-2. else

if <condition>:
    <code_1>
else:
    <code_2>
state = False
if state:
  print('if')
else:
  print('done')

->done

money = 10000
if money >= 30000:
  print('고기를 산다')
else:
  print('고기를 못 산다')

->고기를 못 산다


1-3. elif

- 조건이 여러 개로 구분해서 코드를 실행할 때 사용
- condition_1이 True이면 code_1이 실행, condition_2가 True이면 code_2가 실행
- condition_1과 condition_2가 False이면 code_3이 실행

if <condition_1>:
    <code_1>
elif <condition_2>:
    <code_2>
else:
    <code_3>
a, b = 40, 40
if a<b:
  print('a<b')
if a==b:
  print('a==b')
if a>b:
  print('a>b')

->a==b

a, b = 40, 40
if a<b:
  print('a<b')
elif a==b:
  print('a==b')
else:
  print('a>b')

->a==b

num = 0

if num:
  print('python_1')

num = 1 # 0을 제외하고 다 True

if num:
  print('python_2')

->python_2


1-4. 삼항연산자

- 간단한 if, else 구문을 한 줄의 코드로 표현할 수 있는 방법

A if (조건) else B
# data 변수에 0이면 "zero" 출력, 아니면 "not zero" 출력

data = 1
if data:
    print("not zero")
else:
    print("zero")

->not zero

data = 0
result = "not zero" if data else "zero"
result

->'zero'

# 1: male, 2: female
data = 1
result = 'male' if data == 1 else 'female'
result

->male


2. 반복문 : Loop

- 반복되는 코드를 실행할 때 사용
- while : 조건을 확인해서 조건이 True인 경우에 while문 안에 코드가 반복적으로 실행되는 것
- break : 반복문 중간에 있을 경우 해당 조건은 블록을 탈출하거나 반복문 자체를 탈출한다
- continue : 해당 조건문 블록을 탈출하여 아래 명령문을 실행하지 않고, 다음 반복문 실행 절차를 수행한다
- for : list와 같은 순서가 있는 데이터 집합을 사용해서 그 데이터의 갯수만큼 실행되는 것
- list comprehension

2-1.while

while <condition>:
    <code>
data = 3
while data:
    print(data)
    data-=1
data

->3
2
1
0


2-2.break

- 반복문이 실행되어 중간에 break를 만나게 되면 반복문이 종료된다

# 무한루프
result = 1
while result:
    print(result)
    if result >= 9:
        break
    result += 1
print(result)

->1
2
3
4
5
6
7
8
9
9


2-3.continue

- 순서가 있는 데이터 집합(iterable: 리스트, 튜플)에서 값을 하나씩 꺼내서 변수에 대입시킨 후 데이터 갯수만큼 for 구문 안에 있는 코드를 실행

for <변수> in <순서가 있는 데이터 집합>:
    <code>
ls = [0,1,2,3,4]
for data in ls:
    print(data, end=", ")

->0, 1, 2, 3, 4,

ls = [0,1,2,3,4]
for data in ls:
    if data % 2:
        continue
    print(data, end=" ")

->0 2 4

dic = {"A":1, "B":2}
for key in dic:
    print(key)

->A
B

dic.items()

->dict.items([('A', 1), ('B', 2)])

for key, value in dic.items():
    print(key, value)

->A 1
B 2


1.range

- list를 간편하게 생성해주는 함수
- 함수 : 코드의 집합을 실행시켜주는 방법

range(end)
range(start, end)
range(start, end, stride)
ls = [1,2,3]
first(range(1,4))

->[1, 2, 3]

result = 0
for data in range(10):    # 0~9까지의 합
    result += data
result

->45

list(range(5))

->[0, 1, 2, 3, 4]

list(range(5,10))

->[5, 6, 7, 8, 9]

list(range(10,0,-2))

->[10, 8, 6, 4, 2]


2.enumerate

- 리스트 데이터의 index와 value값을 동시에 사용할 수 있게 해주는 함수

subjects = ["korean", "english", "math", "science"]
number = 1
for subject in subjects:
    print(number, subject)
    number += 1

->1 korean
2 english
3 math
4 science

list(enumerate(subjects))

->[(0, 'korean'), (1, 'english'), (2, 'math'), (3, 'science')]

for idx, subject in enumerate(subjects):
    print(idx+1, subject)

->1 korean
2 english
3 math
4 science


4.zip

- n개의 리스트를 같은 index끼리 묶어주는 함수

subjects = ["korean", "english", "math", "science"]
points = [40,46,70,80]
list(zip(subjects, points))

->[('korean', 40), ('english', 46), ('math', 70), ('science', 80)]

result = {}
for subject, point in zip(subjects, points):
    result[subject] = point
result

->{'korean': 40, 'english': 46, 'math': 70, 'science': 80}


5.random

import random
random.randint(1, 10)

->7

random.choice([1,5,9])

->9


6.List Comprehension

- 리스트 데이터를 만들어주는 방법
- for문보다 빠르게 동작합니다

ls = [0,1,2,3]
result = []

for data in ls:
    result.append(data**2)    # **n : n제곱
result

->[0, 1, 4, 9]

result = [data**2 for data in ls]
result

->[0, 1, 4, 9]

ls = [0,1,2,3]

result = ["홀수" if data%2 else "짝수"
            for data in ls
]
result

->['짝수', '홀수', '짝수', '홀수']