프로그래밍 언어/Python

for문과 while문 비교

ruby-jieun 2023. 1. 7. 18:51

 

 

for문과 while문 비교

 


 

 

for문이 적합한 경우

  • 횟수에 의한 반복이라면 for문이 while문보다 적합하다.
    1부터 10까지의 합을 구하는 경우 for문이 while문보다 코드가 간결하다.

for문

sum = 0
for i in range(1, 11):
    sum += i
print('sum : {}' .format(sum))

while문

sum = 0
n = 1
while n < 11:
    sum += n
    n += 1
print('sum : {}' .format(sum))

 

while문이 적합한 경우

  •  조건에 의한 반복이라면 while문이 for문보다 적합하다.
    1부터 시작해서 7의 배수의 합이 50 이상인 최초의 정수 출력

for문

sum = 0
maxInt = 0
for i in range(1, 101):
    if i % 7 == 0 and sum <= 50:
        sum += i
        maxInt = i

    print('i : {}' .format(i))

print('7의 배수의 합이 50이상인 최초의 정수 : {}' .format(maxInt))

 

while문

sum = 0
maxInt = 0
n = 1
while n <= 100 and sum <= 50:
    n += 1

    if n % 7 == 0:
        sum += n
        maxInt = n

    print('n : {}' .format(n))

print('7의 배수의 합이 50이상인 최초의 정수 : {}' .format(maxInt))