Instances of true and false values of python objects of which are considered False

  • 2021-08-21 20:57:40
  • OfStack

We are no strangers to True and False of python language. We often encounter such return values in the process of learning. What are the specific meanings of True true and False false?

This article will tell you the meaning of true and false in python.

Concepts of truth and falsehood

Like many programming languages 1, true and false in python can also be represented by integers 0 and 1, with integer 0 representing false and integer 1 representing true. In fact, true and python each object is a specific attribute, this attribute is either true or false. In python, all of them are objects, such as data structures, while python regards empty data structures as False false, while non-empty data structures are True true.

Let's look at examples of true and false values of objects in python


"spam"  True 
""    False 
[]    False 
{}    False 
1    True 
0.0   False 
None   False

Role of None

The last None in the above example will be considered as False. In fact, it is the only value of a special object and a special data type in python. Its function is similar to null in C language, and it plays an empty role.

As shown below:


x = [None]*100 
>>> x 
[None, None, None, None, None, None,...] 
>>> 
>>> x[2]='a' 
>>> x 
[None, None, 'a', None, None, None,...]

None plays a placeholder role, and then the content can be replaced by index assignment. It can be seen from this example that None is not without content, it is a real right image, and it has other uses in python.

If you want to really understand the meaning of true and false in Python language, you need to understand more. It is very helpful to understand how to write code.

Supplementary knowledge: the relationship between True, False and 0, 1 in python

demo1


>>> print(True == 1)
>>> print(True == 2)
>>> print(False == 0)
>>> print(False == 2)
True
False
True
False

This shows that 1 and True, and 0 and False are exactly equivalent to python.

demo2


>>> x = 5
>>> if x%2:
>>>   x += 1
>>> else:
>>>   x -= 1
>>> print(x)

In demo2, we can see the wonderful use of the relationship between the two.

x%2=0 < - > x%2 = True


Related articles: