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 문 에서는 어떻게 나타날지도 확인했다.
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
'Python > 분류가 애매함' 카테고리의 다른 글
파이썬 절대 주소값(absolute address) 받아오는 3가지 방법 (0) | 2023.09.15 |
---|---|
DeepLab v3+ 간단한 설명 (0) | 2023.09.13 |
CuDNN을 엔비디아 로그인 없이 다운 받는 꼼수 : The solution of, How to download CuDNN without login NVidia. (0) | 2023.09.13 |
Python에서 glob.glob() 쓸 때 디렉토리 주소 끝에를 /* 로 보정해주는 함수 (0) | 2023.09.13 |
코드 중간중간에 붙이는 주석 codetag(코드태그)의 목록 (0) | 2023.09.13 |