로봇-AI

[파이썬3강]Booleans

happynaraepapa 2024. 12. 27. 14:44

sources:
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

boolean value - 논리값

Python has a type of variable called bool. It has two possible values: True and False.
파이썬에는 Bool이라고 부르는 변수 타입이 있고, 이는 참(True) 혹은 거짓(False) 의 논리값을 가진다.
>>
x = True
print(x)
print(type(x))
>>
True
<class 'bool'>



Rather than putting True or False directly in our code, we usually get boolean values from boolean operators. These are operators that answer yes/no questions. We'll go through some of these operators below.

코딩에서는 True/False를 직접 집어 넣기 보다 이를 논리 연산자(boolean operators)에서 계산되는 논리값(Boolean Values)으로 구현하는 경우가 많다. 이 논리 연산자들은 Yes/No에 대한 대답으로 이루어진 경우가 많다. 예를들면,
...(중략 본문 참고)..

Comparison operators can be combined with the arithmetic operators we've already seen to express a virtually limitless range of mathematical tests.
이런 비교 연산자는 산술 연산자와 혼합해서 사용할 수 있고 다양한 수학적 표현이 가능하다.

For example, we can check if a number is odd by checking that the modulus with 2 returns 1:
예를 들어, 숫자가 홀수 인가를 체크하는 것은 나눠서 나머지가 1인가를 체크하는 것과 같다.
>>
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


Remember to use == instead of = when making comparisons. If you write n == 2 you are asking about the value of n. When you write n = 2 you are changing the value of n.
비교 연산자에서 '같다'의 의미로 '==' 를 사용하는 것을 주의해라. (assign의 경우는 '=')


Combining Boolean Values
You can combine boolean values using the standard concepts of "and", "or", and "not". In fact, the words to do this are: and, or, and not.
우리는 'and', 'or', 'not'과 같은 표준 논리 연산을 논리값(boolean values)과 같이 사용할 수 있다.

With these, we can make our can_run_for_president function more accurate.
이점을 이용하여 우리는 can_run_for_president function 을 좀 더 정확하게 만들 수 있다.

..(중략, 본문참고)..

To answer this, you'd need to figure out the order of operations.
이 점에 답하려면 실행 순서를 알아야 한다.

... (중략)..

You could try to memorize the order of precedence, but a safer bet is to just use liberal parentheses. Not only does this help prevent bugs, it makes your intentions clearer to anyone who reads your code.
만약 우선 순위에 대해 기억하고 있다고 하더라도 경우에 따라서는 괄호를 사용하는 것이 안전할 수 있다. 이는 버그를 예방하기도 하고 코드를 읽기 편하다.

...(중략)...

But not only is my Python code hard to read, it has a bug. We can address both problems by adding some parentheses:
이 코드는 읽기 어려울 뿐만 아니라 버그가 있다. 이 문제를 아래와 같이 괄호를 넣어서 해결할 수 있다.

...(중략)...
We can also split it over multiple lines to emphasize the 3-part structure described above:
또한 위에서 언급된 주요 3단 구조가 드러나도록 여러줄로 나눠서 표현할 수도 있다.

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



Conditionals
Booleans are most useful when combined with conditional statements, using the keywords if, elif, and else.
논리값은 조건문(conditional statement)과 결합되었을때 매우 유용하다. if, elif, else 등이다.

Conditional statements, often referred to as if-then statements, let you control what pieces of code are run based on the value of some Boolean condition. Here's an example:
조건문은 주로 if-then 문으로 표현되는데 특정 논리값에 따라 이하의 코드가 작동되도록 콘트롤 하는   키워드이다. 예를 들어,
...(중략)...
The if and else keywords are often used in other languages; its more unique keyword is elif, a contraction of "else if". In these conditional clauses, elif and else blocks are optional; additionally, you can include as many elif statements as you would like.
if나 else와 달리 elif는 다소 생소할 것인데, 이는 'else if'의 축약형으로 도입된 것이다.
else나 elif는 옵션이며, 원하는 만큼 넣을 수도 있다.

Note especially the use of colons (:) and whitespace to denote separate blocks of code. This is similar to what happens when we define a function - the function header ends with :, and the following line is indented with 4 spaces. All subsequent indented lines belong to the body of the function, until we encounter an unindented line, ending the function definition.
다만 colon(:)이나 스페이스, 들여쓰기 등이 코드의 블록을 형성한다는 점은 주의해야 한다. 함수 헤더가 완료된 뒤 콜론찍고 다음 라인에 들여쓰기를 하고 같은 들여쓰기는 같은 레벨에 있었던 것을 기억하자. (들여쓰기의 레벨이 문장의 상,하위 구조를 대신 표현했다.)
조건문의 콜론 (:)이후도 같은 방법으로 구성된다.
...중략...


Boolean conversion
We've seen int(), which turns things into ints, and float(), which turns things into floats, so you might not be surprised to hear that Python has a bool() function which turns things into bools.
앞에서  int() 함수를 봤다. 이는 ()안에 입력되는 인자를 정수타입으로 변경하는 것이었고, float()는 부동소수로 변경했다.
그러면 bool()은 뭘까?

...(중략)...
We can use non-boolean objects in if conditions and other places where a boolean would be expected. Python will implicitly treat them as their corresponding boolean value:
논리값이 요구되는 경우 논리값이 아닌 오브젝트를 인자로 넣어서 논리값으로 변경해주는 기능을 제공합니다. 파이썬은 해당 오브젝트에  대응되는 불린 값으로 변환해줍니다.
...(이하생략)...