The True and False conditions in Python determine instance analysis

  • 2020-04-02 14:29:31
  • OfStack

This article illustrates the use of True and False conditional judgment in Python. Share with you for your reference. Specific analysis is as follows:

Experienced programmers know how to write conditional statements:
Take C++ as an example:

if (condition)  

    doSomething(); 
}

The rules for writing conditional judgment statements in Python look like this:
if (condition) :   
    doSomething()

So when is an condition true and when is it false in a condition statement?
In high-level languages such as C++/Java, a condition is False if the value is 0 or if the referenced object is a null pointer.
In Python, if condition is '', (), [], {}, None, set(), then the condition is Flase, otherwise True.
Here are the test statements for Python:
1. Test for strings
>>> condition=''  
>>> print 'True' if condition else 'False' 
False 
>>> condition='test' 
>>> print 'True' if condition else 'False' 
True

2. Test against the original group
>>> condition=()  
>>> print 'True' if condition else 'False' 
False 
>>> condition=(1,2) 
>>> print 'True' if condition else 'False' 
True

3. Testing against lists
>>> condition=[]  
>>> print 'True' if condition else 'False' 
False 
>>> condition=['a','b'] 
>>> print 'True' if condition else 'False' 
True

4. Tests for dictionaries
>>> condition={}  
>>> print 'True' if condition else 'False' 
False 
>>> condition={'k':'v'} 
>>> print 'True' if condition else 'False' 
True

5. Testing for None
>>> condition=None  
>>> print 'True' if condition else 'False' 
False

6. Test for set()
>>> condition=set()  
>>> print 'True' if condition else 'False' 
False 
>>> condition.add('a') 
>>> print 'True' if condition else 'False' 
True

I hope this article has helped you with your Python programming.


Related articles: