반응형

30 Days of ML의  Day4!!

Today's Assignment - day 4

 

오늘은Booleans and Conditionals에 대한 내용이다.
Bool은 참 거짓을 나타내는 자료형이다. Conditionals은 조건식에 대한 내용이다. 
오늘도 즐겁게 Assigment를 수행해 보자!

 

Booleans

파이썬은 bool 자료형이 있습니다. 이것이 가지는 value는 True and False입니다.

x = True
print(x)
print(type(x))

위의 코드를 실행하면 뭐가 출력될까요?
x를 True라고 하였으므로 print(x)는 true 가 출력 될 것이고,
print(type(x))는  x의 타입이 출력 될텐데, 지금 x = True이기 때문에 bool자료형이라고 출력이 될 것입니다.

예상한 대로 True와 bool이 출력됐습니다. 

 

Comparison Operations

간단한 표가 있다. 각종 계산을 할 수 있는 기호이다. 잘 알아두자!

def can_run_for_president(age):
    """Can someone of the given age run for president in the US?"""
    # The US Constitution says you must be at least 35 years old
    return age >= 35

print("Can a 19-year-old run for president?", can_run_for_president(19))
print("Can a 45-year-old run for president?", can_run_for_president(45))

위의 코드를 실행하면 어떤것이 출력될까? 
19는 35보다 크거나 같다는, 성립하지 않으므로  False, 그리고 45는 35보다 크거나 같다는 성립하므로 True가 출력될 것이다. 

예상한 것 처럼 출력되는 것을 확인 할 수 있다.

3.0 == 3

위의 코드는 참일까 거짓일까? 3.0은 3이므로 참이다.
따라서 출력해보면 True가 출력된다.

그런데 아래코드를 보자.

'3' == 3

이 코드는 참일까? 
문자3과 숫자3은 엄연히 다르다. 따라서 False가 출력 될 것이다.


이번에는 비교연산자 == 를 알아보자.

def is_odd(n):
    return (n % 2) == 1

print("Is 100 odd?", is_odd(100))
print("Is -1 odd?", is_odd(-1))

홀수를 찾는 함수가 있다.
100을 input하면 100은 짝수이기 때문에 False, -1은 홀수 이기 때문에 True가 출력된다.

그런데, 이때 주의할 점이 있다.
비교를 하려고 하는 것이라면 "="말고 "=="를 사용해야한다.
n == 2 라고 쓰면 n의 값이 2인지 묻는 것이고, n = 2 라고 쓰면 n의 값을 2로 변경하는 것이다.


Combining Boolean Values

and, or, not을 이용하면 더 정확하게 기능을 구현할 수 있다.|

def can_run_for_president(age, is_natural_born_citizen):
    """Can someone of the given age and citizenship status run for president in the US?"""
    # The US Constitution says you must be a natural born citizen *and* at least 35 years old
    return is_natural_born_citizen and (age >= 35)

print(can_run_for_president(19, True))
print(can_run_for_president(55, False))
print(can_run_for_president(55, True))

위의 코드를 실행하면 결과가 어떻게 될까?
첫번째 샘플은 미국시민이지만, 35살이 넘지 않았으므로 최종적으로 False,
두번째 샘플은 35세 이상이지만, 미국시민이 아니므로 최종적으로 False,
세번째 샘플은 35세 이상이고 미국시민이므로 최종적으로 True가 된다.

자 아래의 코드를 보자.

True or True and False

이것의 결과는 무엇일까?

이 질문에 답하려면, 작업의 순서를 파악해야 한다.
하지만, 순서를 외우기 보다는, 괄호를 사용하는 것이 더 안전하다.
그렇게 하면, 버그를 방지 할 수 있을 뿐만 아니라 코드를 읽는 모든 사람들에게 의도를 더 명확히 전달 할 수 있다.

다음식을 보자.

prepared_for_weather = have_umbrella or rain_level < 5 and have_hood or not rain_level > 0 and is_workday

위의 코드는 오늘 날씨로부터 자신은 안전하다는 것을 말하려는 것이다.
우산을 가지고있다면,
혹은, 비가 너무 많이 내리지 않고 후드가 있다면,
그렇지 않으면 나는 비가 오고 일하는 날만 아니면 괜찮다.
라는 조건이 있다.
하지만, 이 파이썬 코드는 읽기 어려울 뿐만 아니라 버그도 있다.
괄호를 추가하여 두 가지 문제를 해결 할 수 있다.

prepared_for_weather = have_umbrella or (rain_level < 5 and have_hood)
or not (rain_level > 0 and is_workday)

가독성에 도움이 된다고 생각될 경우, 더 많은 괄호를 추가할 수 있다.

prepared_for_weather = have_umbrella or ((rain_level < 5) and have_hood)
 or (not (rain_level > 0 and is_workday))

또한 여러 줄로 분할하여 위에서 설명한 3가지 조건의 구조를 강조할 수 있다.

prepared_for_weather = (
    have_umbrella 
    or ((rain_level < 5) and have_hood) 
    or (not (rain_level > 0 and is_workday))
)




Conditionals

bool타입은 조건문과 결합할 때 가장 유용하며, if, elif, else등의 키워드를 사용한다.
조건문은, if then 문이라고도 하며, 일부 bool조건의 값에 따라 실행할 코드를 제어할 수 있다.
다음 예시를 보자

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)
inspect(-15)

elif문은 원하는 만큼 포함 할 수 있다.
특히 콜론(:)과 공백을 사용하여 별도의 코드 블록을 나타낸다. 
이것은 함수를 정의할 때와 유사하다. 함수 헤더는 :로 끝나고 다음 행은 공백 4개로 들여쓴다.

def f(x):
    if x > 0:
        print("Only printed when x is positive; x =", x)
        print("Also only printed when x is positive; x =", x)
    print("Always printed, regardless of x's value; x =", x)

f(1)
f(0)

 

Boolean conversion

파이썬에서 1은 Truel, 0은 False이다. 
그리고 빈문자열을 제외한 모든 문자열은 True(참)으로 처리된다.
일반적으로 비어있는 시퀀스(문자열, 리스트, 튜플)등은  false로 처리되고 나머지는 true로 처리된다.

print(bool(1)) # all numbers are treated as true, except 0
print(bool(0))
print(bool("asf")) # all strings are treated as true, except the empty string ""
print(bool(""))
# Generally empty sequences (strings, lists, and other types we've yet to see like lists and tuples)
# are "falsey" and the rest are "truthy"

bool이 예상되는 조건 및 기타 위치에서 bool이 아닌 개체를 사용할 수 있다. 
python은 암시적으로 이러한 값을 해당 bool값으로 간주한다.

if 0:
    print(0)
elif "spam":
    print("spam")

자 이제 exercise를 수행해 보자!
exercise를 정리한 코드를 공유 한다!! 즐겁게 하자!
https://github.com/mgkim-developer/30-Days-of-ML-with-Kaggle/blob/main/30-days-of-ml-day-4.ipynb

 

GitHub - mgkim-developer/30-Days-of-ML-with-Kaggle: 30 Days of ML with Kaggle

30 Days of ML with Kaggle. Contribute to mgkim-developer/30-Days-of-ML-with-Kaggle development by creating an account on GitHub.

github.com

 

반응형