파이썬(Python)

(3) 파이썬(Python)이란? - Booleans and Conditionals [Hellfer]

Hellfer 2024. 7. 11. 10:45
728x90

https://www.kaggle.com/code/colinmorris/booleans-and-conditionals

 

Booleans and Conditionals

Explore and run machine learning code with Kaggle Notebooks | Using data from No attached data sources

www.kaggle.com

 

위의 글을 보고 참고하여 작성하였습니다.

 

bool이라는 변수 유형은 True와 False라는 두 가지 값이 가능하며 bool 값은 주로 조건문이나 논리 연산에 사용됩니다.

 

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

 

 

비교 연산자에는 6가지 종류가 있습니다.

 

1. a == b : a는 b와 값이 같다.

2. a!= b : a와 b는 값이 다르다.

3. a < b : b가 a보다 크다.

4. a > b : a가 b보다 크다.

5. a <= b : b가 a보다 크거나 같다.

6. b <= a : a가 b보다 크거나 같다.

 

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 19-year-old run for president?", can_run_for_president(45))

 

 

Can a 19-year-old run for president? False

Can a 45-year-old run for president? True

 

- 미국 대통령에 출마하려면 최소 35살이 되어야 하며 19살은 False를 45살은 True을 반환하는 것을 볼 수 있습니다.

 

3.0 == 3
#True

 

'3' == 3
#'3'은 str형이고 3은 int형이기 때문에 False를 반환

 

 

비교연산자는 산술연산자와 결합하여 다양한 수학적 테스트를 수행할 수 있습니다.

 

예를 들어, 숫자가 짝수인지 홀수인지 확인하는 방법을 생각해 볼 수 있습니다.

 

def is_odd(n):
    return (n%2) == 1
    
print("Is 100 odd?", is_odd(100))
print("IS -1 odd?", is_odd(-1))

 

Is 100 odd? False

Is -1 odd? True

 

비교할 때는 = 대신 ==을 써야 합니다. 

n == 3이라면 n이 3인지 묻는 것이고 n = 2 하면 n의 값은 2로 변경됩니다.

 


 

bool 값을 'and', 'or', 'not'의 개념을 사용하여 결합할 수 있습니다. 

 

def can_run_for_president(age, is_natural_born_citizen):
    """Can someone of the given age and citizenship status rum for president in the US?"""
    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))

 

False

False

True

 

True or True and False

 

True

 

- and가 or보다 먼저 평가됩니다.

 


 

 

괄호를 사용하여 가독성을 높이고 오류를 방지할 수 있습니다.

 

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))
)

 

 


 

 

조건문은 'if', 'elif', 'else' 키워드를 사용하여 나타냅니다.

 

'if - then' 문이라고도 하는 조건문을 사용하면 일부 조건에 따라 코드 부분을 제어할 수 있습니다.

 

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)

 

 

0 is zero

-15 is negative

 

if 및 else 키워드는 다른 언어에서도 자주 사용되며 'else if'의 축약형은 'elif'입니다.

 

함수 헤더는 :으로 끝나고 다음 줄은 4개의 공백으로 들여 쓰기 됩니다.

 

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

 

only printed when x is positive; x = 1

Also only printed when is positive; x = 1

Always printed, regardless of x's value; x = 1

Always printed, regardless of x's value; x = 0

 


 

 

bool 함수의 기능은 다음과 같습니다.

 

숫자 : 0은 False로, 그 외의 숫자는 True로 반환됩니다.

문자열 : 빈 문자열 " " 은 False로, 그 외의 문자열은 True로 반환됩니다.

리스트, 튜플, 딕셔너리 등 : 빈 컨테이너는 False로, 있다면 True로 반환됩니다.

 

print(bool(1)) # 0을 제외한 모든 숫자는 True로 처리
print(bool(0))
print(bool("asf")) # 빈 문자열을 제외한 모든 문자열은 True로 처리
print("")

 

728x90