[PYTHON] Basic tech that easily determines whether the value is "yes" or "no"

You can use len () to determine if the list contains or does not have a value, but this is not smart.

sample.py


list_1 = []
if len(list_1) > 0:
    print("list_1 : Not empty")
else:
    print("list_1 : empty")

There is a more concise way to call it:

sample.py


list_1 = [] #Prepare an empty list

if list_1:
    print("list_1 : Not empty :", list_1)
else:
    print("list_1 : empty")

list_1.append(1)    #Add value to empty list

if list_1:
    print("list_1 : Not empty :", list_1)
else:
    print("list_1 : empty")

#Output result
# list_1 : empty
# list_1 : Not empty : [1]

The above if list_1: means "True if any value is included". Very convenient.

In addition, the judgment of True or False by the if statement is as follows. Tuples, lists, and dictionary types can be determined in the same way.

sample.py


empty_1 = ''
empty_2 = ' '
empty_3 = 0
empty_4 = 1
empty_5 = "Hello"

if empty_1:
    print(" ""  : Not empty")
else:
    print(" ''  : empty")

if empty_2:
    print(" ' ' : Not empty")
else:
    print(" ' ' : empty")

if empty_3:
    print(" 0 : Not empty")
else:
    print(" 0 : empty")

if empty_4:
    print(" 1 : Not empty")
else:
    print(" 1 : empty")

if empty_5:
    print(" Hello : Not empty")
else:
    print(" Hello : empty")

#Output result

# ''    : empty
# ' '   : Not empty
# 0     : empty
# 1     : Not empty
# Hello : Not empty

that's all

Recommended Posts

Basic tech that easily determines whether the value is "yes" or "no"
The return value of len or unichr may change depending on whether it is UCS-2 or UCS-4.
A program that determines whether a number entered in Python is a prime number
A program that automatically determines whether an animation or a photo is entered when a person's image is input [python]