Pythonprovidebool
Type, can have two values:True
withFalse
(capital)
done = False
done = True
Boolean for conditional control structures (e.g.if
statement:
done = True
if done:
# run some code here
else:
# run some other code
When evaluating the valueTrue
orFalse
If the value is notbool
Depending on the type to be checked, we have some rules:
- Numbers are always
True
Unless number0
- The string is
False
Only when empty - List, tuple, set, dictionary are
False
Only when empty
You can check whether the value is a boolean in the following ways:
done = True
type(done) == bool #True
Or useisinstance()
, Pass 2 parameters: variables andbool
class:
done = True
isinstance(done, bool) #True
globalany()
The function is also very useful when using boolean values, because it returnsTrue
If any value of the iterable (e.g. list) passed as a parameter isTrue
:
book_1_read = True
book_2_read = False
read_any_book = any([book_1_read, book_2_read])
globalall()
Same function, but returnsTrue
If all the values passed to it areTrue
:
ingredients_purchased = True
meal_cooked = False
ready_to_serve = all([ingredients_purchased, meal_cooked])
More python tutorials:
- Introduction to Python
- 在macOS上安装Python 3
- Run Python program
- Python 2 and Python 3
- Basics of using Python
- Python data types
- Python operators
- Python string
- Python boolean
- Python numbers
- Python, accepts input
- Python control statements
- Python list
- Python tuple
- Python set
- Python dictionary
- Python functions
- Python objects
- Python loop
- Python module
- Python class
- Python standard library
- Debug Python
- Python variable scope
- Python, accept parameters from the command line
- Python recursion
- Python nested functions
- Python Lambda function
- Python closure
- Python virtual environment
- Use Python to use GoPro as a remote webcam
- Python, how to create a list from a string
- Python decorator
- Python Docstrings
- Python introspection
- Python notes
- Python, how to list files and folders in a directory
- Python, how to check if a number is odd or even
- Python, how to get detailed information of a file
- Python, how to check if a file or directory exists
- Python exception
- Python, how to create a directory
- Python, how to create an empty file
- Python, `with` statement
- Python, create a network request
- Python, use `pip` to install third-party software packages
- Python, read file content