본문 바로가기

코딩과 교육/파이썬

03강 제어문/반복문 - if / while / for 문에 대한 학습



◆ 학점 프로그램을 만든다면 ?


점수

학점

점수에 따른 학점의 기준을 만든다

) 95점 이상 A+, 60점 미만 F

첫번째 줄의 점수를 판단

) 96점은 95점 이상이므로 A+

다음 줄로 계속 이동하면서 를 반복

) 51점은 60점 미만이므로 F

더 이상 점수가 없을 때 프로그램 종료

96

 ?

51

 ?

69

 ?

15

 ?


프로그램을 만들 때 조건과 반복은 필수


◆ 조건문이란?

조건에 따라 특정한 동작을 하게 하는 것


if 문은 조건을 판별할 때 사용됩니다. if (만약) 조건이 참이라면, if 블록의 명령문을 실행하며 else (아니면) 면 else 블록의 명령문을 실행합니다. 이 때 else 조건절은 생략이 가능합니다.


if True:

    print('Yes, it is true’)



number = 23

guess = int(input('Enter an integer : '))

if guess == number:

    # New block starts here

    print('Congratulations, you guessed it.')

    print('(but you do not win any prizes!)')

    # New block ends here

elif guess < number:

    # Another block

    print('No, it is a little higher than that')

    # You can do whatever you want in a block ...

else:

    print('No, it is a little lower than that')

    # you must have guessed > number to reach here

print('Done')

# This last statement is always executed,

# after the if statement is executed.



◆ 반복문 : while 

while 문은 특정 조건이 참일 경우 계속해서 블록의 명령문들을 반복하여 실행할 수 있도록 합니다. while 문은 *반복문*의 한 예입니다. 또한 while 문에는 else 절이 따라올 수 있습니다.

 

number = 23

running = True

while running:

    guess = int(input('Enter an integer : '))

    if guess == number:

        print ('Congratulations, you guessed it.')

        # this causes the while loop to stop

        running = False

    elif guess < number:

        print ('No, it is a little higher than that.')

    else:

        print ('No, it is a little lower than that.')

else:

    print ('The while loop is over.')

       # Do anything else you want to do here

print ('Done')



◆ for 루프

for..in 문은 객체의 열거형(Sequence)을 따라서 반복하여 실행할 때 사용되는 파이썬에 내장된 또 하나의 반복문으로, 열거형에 포함된 각 항목을 하나씩 거쳐가며 실행합니다. 열거형에 대해서는 이후에 좀 더 자세히 다룰 것입니다. 일단 여기서는, 열거형이란 여러 항목이 나열된 어떤 목록을 의미한다고 생각하시기 바랍니다.


for i in range(1, 5):

    print (i)

else:

    print ('The for loop is over')



◆ break 문

break 문은 루프 문을 강제로 빠져나올 때, 즉 아직 루프 조건이 `False`가 되지 않았거나 열거형의 끝까지 루프가 도달하지 않았을 경우에 루프 문의 실행을 강제로 정지시키고 싶을 때 사용됩니다.


중요한 점은 만약 여러분이 break 문을 써서 for 루프나 while 루프를 빠져나왔을 경우, 루프에 딸린 else 블록은 실행되지 않습니다.


while True:

    s = input('Enter something : ')

    if s == 'quit':

        break

    print ('Length of the string is', len(s))

print ('Done')


◆ continue 문

continue 문은 현재 실행중인 루프 블록의 나머지 명령문들을 실행하지 않고 곧바로 다음 루프로 넘어가도록 합니다.


while True:

    s = input('Enter something : ')

    if s == 'quit':

        break

    if len(s) < 3:

        print('Too small')

        continue

    print('Input is of sufficient length')

        # Do other kinds of processing here...


HW : 

1. 하나의 숫자를 입력받은 후 1) 짝수인지 여부와 2) 3의 배수인지 여부를 출력

2. 로또 번호 출력기 만들기

2.1. 5개의 로또번호를 만든다.

2.2. 5개의 숫자를 입력받은 후 번호가 맞는지 확인하는 것을 반복한다. 

2.3. 5개 번호가 다 맞으면 5개 번호와 시행횟수를 출력한다.

3. 숫자를 입력받은 후 그 숫자만큼 * 을 출력하는 프로그램

3.1. ******** (한줄로 출력)


 3.2.

 3.3

 3.4

 3.4

3.5 

 3.6

*

**

***

****

*****

    *

   **

  ***

 ****

*****


*****

****

***

**

*

*****

 ****

  ***

   **

    *

    *

   ***

  *****

 *******

*********

*********

 *******

  *****

   ***

    *