1. Booleans
Python은 'bool'이라고 불리는 데이터 타입을 가지고 있다. bool은 'True'와 'False' 값을 가진다.
x = True
print(x)
print(type(x))
# result will be True, <class 'bool'>
'True'와 'False'를 즉시 코드에 쓰는 것보다 불린 연산자(boolean operation)을 통해 bool 값을 얻는 방식을 주로 사용한다. 특히 Pandas library의 데이터 indexing에 자주 쓰인다.
Operation | Description | Operation | Description |
---|---|---|---|
a == b | a equal to b | a != b | a not equal to b |
a < b | a less than b | a > b | a greater than b |
a <= b | a less than or equal to b | a >= b | a greater than or equal to b |
비교 연산자는 수학적 연산자의 조합을 통해 수학적 범위를 다양하게 표현 가능하다. 예를들어, 어떤 숫자가 홀수 인지를 확인하고자 하면 2를 나누었을 때 나머지가 1인지를 확인하면 된다.
def is_odd(n) :
return (n % 2) == 1
print("Is 100 odd?", is_odd(100))
print("Is -1 odd?", is_odd(-1))
# result would be False, True
'=='는 비교를 위해 사용하고, '='는 할당을 위해 사용한다는 차이가 있다.
2. Combining Boolean Values
'and', 'or', 'not'을 이용해 boolean value를 조합할 수 있다.
True and True # True
True and False # False
False and False # False
True or True # True
True or False # False
False or False # False
not True # False
# other can be replaced by &, ||, !
3. Conditionals
Boolean은 if, else, elif를 사용하는 조건문과 조합하여 유용하게 사용된다. 조건문, if-else statement, 는 Boolean 조건을 만족하는 경우에 코드를 실행하게 한다.
def inspect(x) :
if x == 0 :
print(x, "is zero")
elif x > 0 :
print(x, "is positive")
elif x < 0 :
print(x, "is negative")
else :
print(x, "is unlike anything I've ever seen...")
inspect(0)
# result will be 0 is zero.
If와 else의 단어는 다른언어에서도 쓰이지만 elif는 좀더 특이하다. elif는 else-if의 줄임말로 if와 else에 동일한 조건을 다양한 범주로 표현하고자 할 때 elif를 여러번 사용할 수 있다.
Source of the course : Kaggle Course _ Booleans and Conditionals
'Course > [Kaggle] Data Science' 카테고리의 다른 글
[Python] Loops and List Comprehensions (0) | 2022.02.11 |
---|---|
[Python] Lists (0) | 2022.02.11 |
[Python] Functions and Getting help (0) | 2022.02.11 |
[Python] Hello, Python (0) | 2022.02.10 |
Kaggle Course Introduction (0) | 2022.02.10 |