Python

[TIL] 220731 While 과 For 사용

kyra 2022. 7. 31. 20:28

 

while의 맨 처음으로 돌아가기 - continue 사용
>>> a = 0
>>> while a < 10:
...     a = a + 1
...     if a % 2 == 0: continue
...     print(a)
...
1
3
5
7
9

위 문장을 수행할 때 a가 짝수인 경우 print(a) 가 수행되지 않고 다시 while문의 맨 처음으로 돌아가게 된다.


무한 루프 - while True: 사용
>>> while True:
...     print("Ctrl+C를 눌러야 while문을 빠져나갈 수 있습니다.")
...
Ctrl+C를 눌러야 while문을 빠져나갈 수 있습니다.
Ctrl+C를 눌러야 while문을 빠져나갈 수 있습니다.
Ctrl+C를 눌러야 while문을 빠져나갈 수 있습니다.
....

 

또 다음과 같이 True 대신 조건을 나누어줄 수 있다.

cont = 1
while cont == 1: #True 대신 1을 사용
	my = input()
	if my in rcp_dict.keys():
		my = int(rcp_dict[my])
		cont = 0  #원하는 문장을 수행 후 조건을 0으로 바꿔 while문 끝내기
	elif my in rcp_dict.values():
		my = int(my)
		cont = 0
	else:
		print('가위, 바위, 보, 혹은 0, 1, 2 중에 입력해주세요.')

 


while 강제로 빠져나가기 - break

무한 루프 안에서 break를 통해 바로 빠져나갈 수 있다.

 

 


For문과 continue

for문 안의 문장을 수행하는 도중에 continue문을 만나면 for문의 처음으로 돌아가게 된다.

 


When to use "while" or "for" in Python

https://stackoverflow.com/questions/920645/when-to-use-while-or-for-in-python

 

When to use "while" or "for" in Python

I am finding problems in when I should use a while loop or a for loop in Python. It looks like people prefer using a for loop (less code lines?). Is there any specific situation which I should use ...

stackoverflow.com

 

<for>

- iterates through a collection or iterable object or generator function.

- set, tuple, list, map or even a string is already an iterable collection, so we simply use a for loop.

- for is more pythonic choice for iterating a list since it is simpler and easier to read

 

<while>

- simply loops until a condition is False

- if there isn't a tidy data structure to iterate through

- indefinite iteration that is used when a loop repeats unknown number of times and end when some condition is met