[Python 기초 정리] 흐름 제어

서해빈·2021년 4월 18일
0

python

목록 보기
4/5

몰랐거나 잊어버리기 쉬운 내용을 정리했습니다.

흐름 제어

1. If

1.1 참/거짓 판별

  • True : "values", [values], (values), {values}, 1
  • False : "", [], (), {}, 0, None

1.2 산술, 관계, 논리 우선순위

산술 > 관계 > 논리 순서로 적용

  • 산술: +, -, *, /
  • 관계: >, >=, <, <=, ==, !=
  • 논리: and, or, not
>>> print(5 + 10 > 0 and not 7 + 3 == 10)
False

1.3 Comparison Chaining

아래와 같은 조건도 가능하다.

if (a < b < c): # 가능. a < b and b < c와 동일하다.
...
if (a < b > c): # 가능. a < b and b > c와 동일하다.
...

comparison chaining

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.

Note that a op1 b op2 c doesn’t imply any kind of comparison between a and c, so that, e.g., x < y > z is perfectly legal (though perhaps not pretty).

2. for

for 문
(C처럼) 사용자가 이터레이션 단계와 중지 조건을 정의할 수 있도록 하는 대신, 파이썬의 for 문은 임의의 시퀀스 (리스트나 문자열)의 항목들을 그 시퀀스에 들어있는 순서대로 이터레이션 합니다.

문법

for i in <collection>:
    <loop body>

2.1 range

Built-in Function range

class range(stop)
class range(start, stop[, step]) # [start, stop)

The range type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.

  • start: The value of the start parameter (or 0 if the parameter was not supplied)
  • stop: The value of the stop parameter
  • step: The value of the step parameter (or 1 if the parameter was not supplied)

Range objects implement the collections.abc.Sequence ABC, and provide features such as containment tests, element index lookup, slicing and support for negative indices.

>> r = range(0, 20, 2)
>> r
range(0, 20, 2)
>> 11 in r
False
>> 10 in r
True
>> r.index(10)
5
>> r[5]
10
>> r[:5]
range(0, 10, 2)
>> r[-1]
18

2.2 Iterables

많은 경우에 range()가 돌려준 객체는 리스트인 것처럼 동작하지만, 사실 리스트가 아닙니다. 이터레이트할 때 원하는 시퀀스 항목들을 순서대로 돌려주는 객체이지만, 실제로 리스트를 만들지 않아서 공간을 절약합니다.

이런 객체를 이터러블 이라고 부릅니다. 공급이 소진될 때까지 일련의 항목들을 얻을 수 있는 무엇인가를 기대하는 함수와 구조물들의 타깃으로 적합합니다. 우리는 for 문이 그런 구조물임을 보았습니다.

문자열, 리스트, 튜플, 집합, 사전 -> iterable
iterable 리턴 함수 : range, reversed, enumerate, filter, map, zip

2.3 break, continue, else

break 문은, C처럼, 가장 가까이서 둘러싸는 for 나 while 루프로부터 빠져나가게 만듭니다.

루프 문은 else 절을 가질 수 있습니다; 루프가 이터러블의 소진이나 (for의 경우) 조건이 거짓이 돼서 (while의 경우) 종료할 때 실행됩니다. 하지만 루프가 break 문으로 종료할 때는 실행되지 않습니다.

루프와 함께 사용될 때, else 절은 if 문보다는 try 문의 else 절과 비슷한 면이 많습니다: try 문의 else 절은 예외가 발생하지 않을 때 실행되고, 루프의 else 절은 break가 발생하지 않을 때 실행됩니다.

3. while

while <expr>:
    <statement(s)>

while 문도 for 문처럼 else 문을 사용할 수 있다. (break시에는 실행 x)

0개의 댓글