Python

(아카이브 22.01.05) 부스트코스 - 처음 배우는 프로그래밍 2강 리뷰

디디 ( DD ) 2022. 12. 17. 00:43

 

2-1. if 조건문과 while 반복문

 

 

 

(예시 1)

 

if it rains:                                                         → 조건

     listen_to_cs101_lecture()                          → 조건이 참이면, 이 작업을 수행

else:

     eat_strawberries_in_the_sun()                  → 조건이 거짓이면, 이 작업을 수행

 

 

 

(예시 2)

 

if True:                                                                               ※ 첫 글자 T는 대문자로! ※

     print("CS101 is my favorite course")                       → 조건이 언제나 참이므로 문장이 출력됨

 

if False:

     print("Every CS101 student will receive an A+")      → 조건이 거짓이므로 출력 X

 

if 3 < 5:

print("3 is less than 5")                                                  → 출력 O

else:

print("3 is larger than 5")                                               → 출력 X

 

 

 

(예시 3) 비퍼 감지

출처 : 부스트코스( https://www.boostcourse.org/cs114 )

 

def move_and_pick():

     hubo.move()

     if hubo.on_beeper():

          hubo.pick_beeper()

for i in range(9):

     move_and pick()

 

 

⇒ 반대로 현재 로봇의 위치에 비퍼가 없을 때, 비퍼를 떨어뜨리려면?

 

if not hubo.on_beeper():                          → not 키워드는 조건을 반대로 바꿔줌.

     hubo.drop_beeper()                                ( not True = False, not false = True )

                                                                     예) print(not 3 < 5)면 False가 화면에 찍힘.

 

 

(예시 4)

 

Q. 로봇이 세계의 경계선을 따라 (반시계 방향으로) 움직이게 하려면?

출처 : 부스트코스( https://www.boostcourse.org/cs114 )

 

def move_or_turn():

    if hubo.front_is_clear():

         hubo.move()

    else:

         hubo.turn_left()

for i in range(20):

    move_or_turn()

 

 

⇒ +춤추기 +모서리에 비퍼 떨어뜨리기

 

def dance():

    for i in range(4):

         hubo.turn_left()

def move_or_turn():

     if hubo.front_is_clear():

          dance()

          hubo.move()

     else:

          hubo.turn_left()

          hubo.drop_beeper()                    ※들여쓰기 주의※

for i in range(18):

     move_or_turn()

 

 

(예시 5)

 

if hubo.on_beeper():

     hubo.pick_beeper()

else:

     if hubo.front_is_clear():

          hubo.move()

     else:

          if hubo.left_is_clear():

               hubo.turn_left()

          else:

               if hubo.right_is_clear():

                    turn_right()

               else:

                    turn_around()

 

⇒ 너무 복잡. 이럴 때 쓸 수 있는 게 elif 구문(else+if).

 

if hubo.on_beeper():

     hubo.pick_beeper()

elif hubo.front_is_clear():

     hubo.move()

elif hubo.left_is_clear():

     hubo.turn_left()

elif hubo.right_is_clear():

     turn_right()

else:

     turn_around()

 

 

· for 반복문 : 정해진 횟수만큼 명령을 반복.

· while 반복문 : 주어진 조건이 참이면, 명령을 계속 반복

 

 

(예시 6)

 

while not hubo.on_beeper():

     hubo.move()

 

→ 비퍼를 발견하기 전까지 계속 전진.

 

 

 

 

 

2-2. if와 while을 사용한 미로 탈출 예제

 

 

 

(예시) 80일간의 세계일주

 

 

Q. 로봇이 시작점에 다시 도착할 때까지 (단순 사각형 모양) 세계의 경계선을 따라 움직이게 하려면?

 

hubo.drop_beeper()

hubo.move()                                   → 이 부분이 없으면 움직이지 않음

while not hubo.on_beeper():

     if hubo.front_is_clear():

          hubo.move()

     else:

          hubo.turn_left()

 

 

⇒ 우회전이 필요한 경우

출처 : 부스트코스( https://www.boostcourse.org/cs114 )

 

hubo.drop_beeper()

hubo.move()

while not hubo.on_beeper():

     if hubo.right_is_clear():

          turn_right()

          hubo.move()                    → 이 부분이 없으면 한자리에서 계속 돔(무한 루프에 빠짐)

     elif hubo. front_is_clear():

           hubo.move()

     else:

           hubo.turn_left()

 

 

 

⇒ 다양한 조건/환경의 world에서도 실행되는 프로그램 만들기

출처 : 부스트코스( https://www.boostcourse.org/cs114 )

 

hubo.drop_beeper()

while not hubo.front_is_clear():          → 조건 추가

     hubo.turn_left()                                   (cf) 여기서 if를 쓰게 되면, 딱 한번 조건을 확인하게 되므로 문제 발생.

     hubo.move()

while not hubo.on_beeper():

     if hubo.right_is_clear():

          turn_right()

          hubo.move()

     elif hubo. front_is_clear():

           hubo.move()

     else:

           hubo.turn_left()

 

 

 

 

 사람이 이해하기 좋은 코드를 작성하기!

→ comment 영역 입력 ( # 뒷부분은 파이썬이 실행하지 않고, 사람이 읽고 이해하도록 남겨놓는 영역임.)

→ 코드에 의미있는 이름 붙이기 (정의할 때, 나중에 상세한 코드를 다시 보지 않아도 알 수 있도록)

 

1) 간단하게 시작하기

2) 한 번에 하나의 작은 작업만 수행하기 (Refinement 상세화)

3) 각각의 작업들이 이전 작업에 영향 주지 않게 하기 (새로 더한 작업이 이전 작업을 망치지 않도록)

4) 알기 쉬운 유용한 주석 달기 ( 파운드사인(#) 이용. 프로그램 명령들을 있는 그대로 쓰지X)

5) 의미를 잘 전달하는 이름 고르기

 

 

 

✔ 실행 안됨. 나중에 다시 확인. (모듈 문제?)

 

 

 

 

 

<키워드 정리>

if, else 만약, 아니라면

True(not False), False(not True), 첫 글자 대문자 주의

들여쓰기 주의!

elif(else+if)

while 참이면 계속 반복

주석 쓸 땐 #

 

 

 

 

 

 

 

 

 

 

☞ pc 화면에 최적화된 개인 복습용 기록입니다.