Method for python to judge whether the output result of all function is true

  • 2021-08-12 03:08:27
  • OfStack

We all learn to judge whether it is true or false. Depending on the conditions, the final output may be true or false. In the function of python, there is also a built-in function that needs to be judged conditionally, so under what circumstances can we ensure that its output result is true? Today, we have a simple code experience on the judgment of all function, and then analyze the output of all function under different conditions.

Built-in function all

Receives 1 iterable object and returns True if all the elements in it are True, or if there are no elements in the iterable object

Equivalent to


def all(iterable):
  for element in iterable:
    if not element:
      return False
return True

Description:

1. Accept 1 iterator object as a parameter, and report an error when the parameter is null or not iterator object


>>> all(2) # Incoming value error report 
Traceback (most recent call last):
 File "<pyshell#9>", line 1, in <module>
  all(2)
TypeError: 'int' object is not iterable

2. Returns True if the logical value of each element in the iterable object is True, otherwise False


>>> all([1,2]) # The logical value of each element in the list is True , return True
True
>>> all([0,1,2]) # In the list 0 The logical value of is False , return False
False

3. If the iterable object is empty (number of elements is 0), return True


>>> all(()) # Empty tuple 
True
>>> all({}) # Empty dictionary 
True

The above is our analysis of judging that the output result of all function is true. What we need to pay attention to is the change of output conditions, and the corresponding result will also change.


Related articles: