Boolean operations and true and false values

高洛峰
Release: 2016-10-19 15:03:30
Original
1814 people have browsed it

In python, any object can determine its true or false value: True, False

In the if or while conditional judgment, the following situation value is False:


1.None

2.Flase

3. When the value is 0, such as: 0,0.0,0j

4. All empty sequences, such as: '', (), []

5. All empty mappings, such as: {}

6.instances of user-defined classes, if the class defines a __bool__() or __len__() method,

when that method returns the integer zero or bool value False.


All other values ​​are considered true — so objects of many types are always true.



In operation operations and built-in functions, the Boolean result is returned 0 or False means false

1 or True means true

Boolean operations in python are as follows:

print('x or y -> if x is false,then y, else x ')
x, y = 2, 0
print('{} or {} = {}'.format(x, y, x or y))
x1, y1 = 0, 10
print('{} or {} = {}'.format(x1, y1, x1 or y1))
x2, y2 = 0, 0
print('{} or {} = {}'.format(x2, y2, x2 or y2))
  
print('#' * 50)
print('x and y -> if x is false,then x, else y ')
print('{} and {} = {}'.format(x, y, x and y))
x1, y1 = 0, 10
print('{} and {} = {}'.format(x1, y1, x1 and y1))
x2, y2 = 0, 0
print('{} and {} = {}'.format(x2, y2, x2 and y2))
  
print('#' * 50)
print('not x -> if x is false,then True,else False ')
x = 2
print('not {} = {}'.format(x, not x))
x = 0
print('not {} = {}'.format(x, not x))
Copy after login

Run result:

>>>>

x or y -> if x is false,then y, else x

or 0 = 2

or 10 = 10

or 0 = 0

#### ############################################

x and y -> if x is false,then x, else y

and 0 = 0

and 10 = 0

and 0 = 0

################# ################################

not x -> if x is false,then True,else False

not 2 = False

not 0 = True

>>>



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!