Python/Study

python 기초 - if, for, while, break, continue (+한줄수식)

pybi 2023. 1. 15. 15:11

1. if

if는 조건이 만족하면, elif는 추가 조건 else는 위의 조건이 모두 만족하지 않는다면 적용된다.

 

예제1 - if에 or 조건 사용

AA = 1
BB = 1
CC = 1

if AA == 1 or BB == 2:
    print("IF")
elif CC == 1:
    print("ELIF")
else:
    print("ELSE")
IF

 

예제2 - if에 and 조건 사용

AA = 1
BB = 1
CC = 1
if AA == 1 and BB == 2:
    print("IF")
elif CC == 2:
    print("ELIF")
else:
    print("ELSE")
ELSE

 

 

2. for

for 는 리스트에 있는것들을 하나씩 꺼내서 반복해서 실행한다.

2-1. list를 하나씩 print

for for_test in [ "A", "B", "C", "D"]:
    print(for_test)
A
B
C
D

 

2-2. range를 사용하여 하나씩 print

for for_test in range(0,5):
    print(for_test)
0
1
2
3
4

 

2-3. 한줄로 수식 추가 (더하기)

one_for = [1,2,3]
print(one_for)
one_for = [i + 10 for i in one_for]
print(one_for)
[1, 2, 3]
[11, 12, 13]

 

2-4. 한줄로 수식 추가 (곱하기)

one_for = [1,2,3]
print(one_for)
one_for = [i * 10 for i in one_for]
print(one_for)
[1, 2, 3]
[10, 20, 30]

 

 

3. while

while은 for와 유사하지만 조건을 만족할 때가지 계속 수행

index = 1
while index < 5 :
    print(index)
    index += 1
1
2
3
4

 

 

4. break

break이 나오면 추가 진행 없이 반복 구문을 바로 종료한다.

index = 1
while index < 5 :
    if index == 3 :
        break
    print(index)    
    index += 1
1
2

 

 

5. continue

continue는 해당 조건에 만족하는 경우 해당 항목은 제외하고 나머지 리스트 값에 대해서 반복 구문을 수행한다.

for for_test in [ "A", "B", "C", "D"]:
    if for_test == "C":
        continue
    print(for_test)
A
B
D

 

끝!