boolean
True, False 두 값을 가질 수 있다. 첫 글자를 대문자로 써줘야 한다.
1
2
3
4
5
|
is_thirsty = False
if is_thirsty == True:
print("Go and Drink some water")
else:
print("Stay")
|
cs |
is_thirsty 는 boolean 타입으로 False를 가지기 때문에 "Stay" 가 console에 출력될 것이다.
이 코드는 아래와 같이 쓸 수 있다.
1
2
3
4
5
|
is_thirsty = False
if is_thirsty:
print("Go and Drink some water")
else:
print("Stay")
|
cs |
조건문에서 if나 elif 뒤의 표현식은 boolean 값을 도출한다.
위와 같이 is_thirsty == True: 로 물어보았을 땐 표현식이 맞으면 True가 되고,
아래에서 is_thirsty만 넣어주었을 땐 그 값 자체를 확인한다.
값 및 변수 평가
True 혹은 False는 bool() 함수를 사용하면 확인할 수 있다.
1
2
3
4
|
bool("Hello") // True
bool(15) // True
bool(0) // False
bool([]) // False
|
cs |
대부분의 값이 있는 경우는 True로 평가되고, 일부는 False로 평가된다.
자료형 | True | False |
str | "python" | "" |
num | 0이 아닌 숫자 | 0 |
list | [1, 2, 3] | [] |
tuple | ("a", "b", "c") | () |
dict | {"hour": 21, "min": 27} | {} |
bool | True | False |
None |
자료를 가져와서 있는지 확인하고, 있으면 다음 과정을 진행하도록 하면
많은 오류를 막을 수 있다.
1
2
3
4
5
6
7
|
pagination = soup.find("nav")
if pagination:
pages = pagination.find_all("li")
last_page = pages[-2].find("a").text
return int(last_page)
else:
return None
|
cs |
함수의 return 값으로 bool을 반환할 수 있다.
1
2
3
4
5
6
7
|
def myFunction() :
return True
if myFunction():
print("YES!")
else:
print("NO!")
|
cs |
참고한 사이트
www.w3schools.com/python/python_datatypes.asp
Python Data Types
Python Data Types Built-in Data Types In programming, data type is an important concept. Variables can store data of different types, and different types can do different things. Python has the following data types built-in by default, in these categories:
www.w3schools.com
www.w3schools.com/python/python_booleans.asp
Python Booleans
Python Booleans Booleans represent one of two values: True or False. Boolean Values In programming you often need to know if an expression is True or False. You can evaluate any expression in Python, and get one of two answers, True or False. When you comp
www.w3schools.com
지금은 개발중
개발 일지, 개발 공부, 일본어 공부등을 포스팅하는 블로그입니다.
myksb1223.github.io
'Python' 카테고리의 다른 글
Python #01-2 String (0) | 2021.04.08 |
---|---|
Python #01 데이터 타입 (0) | 2021.04.08 |