3 제어 구조

2023. 10. 22. 23:13프로그래밍 공부/Python

3.1 제어 구조란?

제어 문장(control statement): 명령 집합의 제어 흐름을 결정하는 문장
제어 구조(control structure): 명령어들과 명령어들의 실행을 제어하는 제어문들의 집합

프로그래밍에서 제어의 세가지 기본적인 형태는 순차적 제어(sequential control), 선택적 제어(selection control), 그리고 반복적인 제어(iterative control)이다.

 

 

3.2 불리언 표현(Boolean Expressions) (조건문(Conditions))

불리언 자료형(Boolean data type): 2개의 Boolean 값을 가짐. (True and False)

불리언 표현(Boolean Expression): Boolean 값을 평가한 표현


3.2.1 관계 연산자(Relational Operators)

관계 연산자 결과
== equal 10 == 10 True
!= not equal 10 != 10 False
< less than 10 < 20 True
> greater than 'Alan' > 'Brenda' False
<= less than or equal to 10 <= 10 True
>= greater than or equal to 'A' >= 'D' False

관계 연산자는 순서가 있는 모든 값 집합에 적용할 수 있다.


3.2.2 멤버 연산자(Membership Operators)

회원 연산자 결과
in 10 in (10, 20, 30) True
  red in ('red', 'green', 'blue') True
not in 10 not in (10, 20, 30) False)

Python은 특정 값이 지정된 값 목록에 있는지 여부를 결정하기 위한 in, not in 멤버 연산자를 제공한다.


3.2.3 불리언 연산자(Boolean Operators)

x y x and y x or y not x
False False False False True
True False False True False
False True False True True
True True True True False

Boolean 논리 진리표

Python의 불리언 연산자는 and, or, not으로 표시된다.


3.2.4 연산자 우선 순위(Operator Precedence)와 불리언 표현(Boolean Expressions)

연산자 우선 순위(Operator Precedence): 주어진 연산자 우선 순위표에 의해 정의된 식을 평가할 때 연산자가 적용되는 상대 순서

Operator(연산자) Associativity(연관성)
**(exponentiation) right-to-left 오른쪽 -> 왼쪽
-(negation) left-to-right 왼쪽 -> 오른쪽
*(multiplication), /(division) , //(truncating div), %(modulo) left-to-right 왼쪽 -> 오른쪽
+(addition), -(subtraction) left-to-right 왼쪽 -> 오른쪽
<,>,<=,>=,!=,== (relational operators) left-to-right 왼쪽 -> 오른쪽
not left-to-right 왼쪽 -> 오른쪽
and left-to-right 왼쪽 -> 오른쪽
or left-to-right 왼쪽 -> 오른쪽

Python에서 산술, 관계, 불리언 연산자의 연산자 우선 순위


3.2.5 짧은 순회(게으름) 평가

짧은 순회(게으름) 평가(Short-Circuit (Lazy) Evaluation)에서 부울 연산자의 두 번째 피연산자와 부울 식의 값이 첫 번째 피연산자 단독에서 결정될 수 있는지 여부를 평가하지 않는다.

ex)

if n ! = 0 and 1/n < tolerance:

n = 0이면 divide by zero 오류가 난다.

옳은 표현

if n != 0:
    if 1/n < tolerance:


3.2.6 논리적으로 동일한 불리언 식 (Logically Equivalent Boolean Expressions)
논리적으로 동일한 Boolean 식 형태

x < y is equivalent to not (x >= y)
x <= y is equivalent to not (x > y)
x == y is equivalent to not (x != y)
x != y is equivalent to not (x == y)
not (x and y) is equivalent to (not x) or (not y)
not (x or y) is equivalent to (not x) and (not y)

 

3.3 선택적 제어(Selection Control)

선택적 제어문(selection control statement): 선택적 실행을 제공하는 제어문

 

3.3.1 If 문 (If statement)

if condition:

    statements

else:

    statements

 

ex)

if grade >= 70:

    print('passing grade')

else:

    print('failing grade')

if 문: 주어진 부울 식의 값을 기반으로 하는 선택 제어문
복합문: 다른 문장을 포함하는 문장

 

3.3.2 들여쓰기(Indentation) in Python

일반적인 프로그래밍 언어에서 들여쓰기는 가독성을 높이기 위한 보조 수단에 불구하지만

파이썬에서는 들여쓰기는 코드의 실행 단위를 구별해주는 요소이므로 중요하다.

 

헤더(header): 키워드로 시작하여 콜론으로 끝난다.

스위트(suite)(= 블록(block)): 헤더 뒤에 오는 문 그룹 

절(clause): 헤더 + 스위트

ex)

1 if score > 90:

2    print('lalala')

3    print('I am happy')

4 else:

5.  print('uuu')

6.  print('I am sad')

헤더: 1번째 줄이 첫번째 헤더, 4번째 줄이 두번째 헤더

스위트: 2~3이 첫번째 스위트, 5~6이 두번째 스위트

절: 1~3번째가 첫번째 절, 4~6번째가 두번째 절

 

3.3.3 다방면의 선택

If 중첩문(Nested if Statements)

문을 Python에 중첩할 수 있는 경우 다중 선택이 발생한다.

elif 헤더(The elif Header in Python)

문장에 여러 개의 elif 헤더가 포함될 수 있는 경우 다중 선택을 제공한다.

 

3.4 반복 제어(Iterative Control)

반복 제어문(Iterative Control Statement): 일련의 문을 반복적으로 실행할 수 있는 제어문

 

3.4.1 While 문(While Statement)

while 문: 제공된 부울 식을 기반으로 문 집합을 반복적으로 실행하는 반복 제어문

while condition:

    suite

 

ex)

sum = 0

current = 1

 

n = int(input('Enter value: '))

 

while current <= n:

    sum = sum + current

    current = current + 1

 

3.4.2 입력 오류 확인

while 문은 입력 오류 검사에 매우 적합하다.


3.4.3 무한 루프

무한 루프(Infinite loop): 절대로 종료되지 않는 반복적인 제어 구조(또는 결국 시스템 오류로 종료된다).

ex)

sum = 0

current = 1

 

n = int(input('Enter value: '))

 

while current <= n:

    sum = sum + current


3.4.4 확정 vs. 불확정 루프

확정 루프(definite loop): 루프가 실행되기 전에 루프가 반복되는 횟수를 결정할 수 있는 프로그램 루프

불확정 루프(indefinite loop): 루프가 실행되기 전에 루프가 반복되는 횟수를 알 수 없는 프로그램 루프

 

확정 루프 예시)

sum = 0

current = 1

 

n = int(input('Enter value: '))

 

while current <= n:

    sum = sum + current

    current = current + 1

 

불확정 루프 예시)

which = input("Enter selection: ")
while which ! = 'F' and which ! = 'C':
    which = input("Please enter 'F' or 'C': ")

 

3.4.5 부울 플래그와 불확정 루프

부울 플래그(Boolean Flag): 주어진 제어 문의 조건으로 사용되는 단일 부울 변수

 

'프로그래밍 공부 > Python' 카테고리의 다른 글

5 함수  (0) 2023.10.23
4 리스트  (1) 2023.10.23
2 데이터와 표현  (0) 2023.10.21
1 소개  (0) 2023.10.21
파이썬 기초 개요  (0) 2023.10.21