Python/분류가 애매함

break, continue, pass 차이 알아보기 (chatGPT 활용)

공시탈출넘버원 2024. 2. 22. 17:29

break, continue, pass 를 맞게 구분해보려고 chatGPT를 사용하여 코드를 만들고 돌려보면서 연습했다.

 

# Example using break, continue, and pass statements

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Using break statement
print("Using break:")
for num in numbers:
    if num == 5:
        break  # Exit the loop if the number is 5
    print(num)
print("End of loop using break\n")

# Using continue statement
print("Using continue:")
for num in numbers:
    if num % 2 == 0:
        continue  # Skip even numbers
        print("can this come out after continue?")
    print(num)
print("End of loop using continue\n")

# Using pass statement
print("Using pass:")
for num in numbers:
    if num % 3 == 0:
        pass  # Do nothing for numbers divisible by 3
        print("can this come out after pass?")
    # in this case, using continue or pass gives the same result
    # don't use pass if you have any action inside if-condition. it is useless. use continue instead.
    else:
        print(num)
print("End of loop using pass")

 

>>>

더보기

Using break:
1
2
3
4
End of loop using break

Using continue:
1
3
5
7
9
End of loop using continue

Using pass:
1
2
can this come out after pass?
4
5
can this come out after pass?
7
8
can this come out after pass?
10
End of loop using pass

 

이중 for 문 에서는 어떻게 나타날지도 확인했다.

break, continue, pass work in double (inner-outer)-for-loop

for i in range(1, 4):
    print(f"1st loop iteration {i}")
    for j in range(1, 4):
        if i == 2 and j == 2:
            print("Encountered break; stopping the inner loop")
            break
        elif i == 2 and j == 1:
            print("Encountered continue; skipping this iteration")
            continue
        elif i == 3 and j == 2:
            print("Encountering pass")
            pass
            print("Encountered pass; doing nothing")
        print(f" 2nd loop iteration {j}")
    print("End of 2nd loop iteration\n")
더보기

1st loop iteration 1
 2nd loop iteration 1
 2nd loop iteration 2
 2nd loop iteration 3
End of 2nd loop iteration

1st loop iteration 2
Encountered continue; skipping this iteration
Encountered break; stopping the inner loop
End of 2nd loop iteration

1st loop iteration 3
 2nd loop iteration 1
Encountering pass
Encountered pass; doing nothing
 2nd loop iteration 2
 2nd loop iteration 3
End of 2nd loop iteration