Files
python-examples/doc/06_flow_controls.md
2025-01-16 21:31:37 +09:00

128 lines
2.0 KiB
Markdown

# 흐름 제어
## 조건문
### if
`if`문의 조건식 뒤에 콜론(`:`)을 붙이고 `if` 블록은 들여쓰기를 합니다.
```python
if 조건식:
실행문
```
```python
if 조건식:
실행문
else:
실행문
```
```python
if 조건식:
실행문
elif 조건식:
실행문
else:
실행문
```
### match case
Python 3.10에서 추가된 문법입니다.
```python
match (n):
case 1: return 'One'
case 2: return 'Two'
case _: return 'Many'
```
```python
case "a" | "b" : return "A or B"
```
```python
case [time, name] :
return f"{time}, {name}!\n"
case [time, *names] :
msg = ''
for name in names:
msg += f"{time}, {name}!\n"
return msg
```
```python
case [item, amount] if amount < 1000:
return amount * 1.2
case [item, amount] if amount >=1000:
return amount * 1.5
```
## 반복문
### for in
```python
for 변수 in range(횟수):
실행문
```
`range`외에 리스트, 튜플, 문자열 등의 시퀀스 타입을 사용해도 됩니다.
```python
a = [1, 2, 3, 4, 5]
for i in a:
print(i)
for i in range(len(a)):
print(a[i])
# 리스트의 인덱스도 필요한 때에는 enumerate()를 사용하면 됩니다.
for idx, val in enumerate(a):
print(idx, val)
```
```python
for i in a:
# 반복적으로 처리.
else:
# 반복문이 정상적으로 종료될 떄 한 번만 수행됩니다.
# break 등으로 반복이 종료되면 이 블록은 실행되지 않습니다.
```
### while
```python
while 조건식:
실행문
```
```python
i = 0
while i <= len(a):
print(a[i])
i += 1
```
```python
while i<10:
# ...
else:
# ...
```
## 그 외
### break
### continue
### pass
써 넣을 실행문이 없을 경우에 사용합니다. Python의 들여쓰기 문법 때문에 사용되는 키워드입니다.
파이썬 3.x부터는 `...`을 사용해도 됩니다.
```python
for i in range(10):
pass # 아무 것도 실행되지 않습니다.
```