Home  >  Article  >  Backend Development  >  The most concise way to write conditional judgment statements in Python

The most concise way to write conditional judgment statements in Python

高洛峰
高洛峰Original
2016-10-17 11:54:201589browse

This article mainly introduces tips for returning true or false values ​​​​(True or False) in Python. This article discusses the most concise way to write conditional judgment statements. This article gives two concise writing methods. Friends who need it can refer to it

As follows A piece of code:

def isLen(strString):
    if len(strString)>6:
        return True
    else:
        return False

Maybe you have discovered that in Python 3 there is actually a way to complete the function in just one line:

The code is as follows:

>>> def isLen(strString):
       return True if len(strString)>6 else False

But. . . Could it be simpler?

How to use Python to express conditional statements more easily, just for fun :)

One way is to use list index:

The code is as follows:

>>> def isLen(strString):
       #这里注意false和true的位置, 多谢网友@小王的指正
       return [False,True][len(strString)>6]

The principle is very simple, the Boolean value True is evaluated as 1 by the index, and False is equal to 0. Can it be simpler

Statement:
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