Я понимаю, что Pythonic способ проверки True и None, а не None:
Код: Выделить всё
if bool_flag:
print("This will print if bool_flag is True")
# PEP8 approved method to check for True
if not bool_flag:
print("This will print if bool_flag is False or None")
# Also will print if bool_flag is an empty dict, sequence, or numeric 0
if bool_flag is None:
print("This will print if bool_flag is None")
if bool_flag is not None:
print("This will print if bool_flag is True or False")
# Also will print if bool_flag is initialized as anything except None
Код: Выделить всё
if bool_flag:
print("This will print if bool_flag is True")
elif bool_flag is None:
print("This will print if bool_flag is None")
else:
print("This will print if bool_flag is False")
# Note this will also print in any case where flag_bool is neither True nor None
Написать «более питонично»:
Код: Выделить всё
# Option A:
if isinstance(bool_flag, bool) and not bool_flag:
print("This will print if bool_flag is False")
# Option B:
if bool_flag is not None and not bool_flag:
print("This will print if bool_flag is False")
## These two appear to be strictly prohibited by PEP8:
# Option C:
if bool_flag is False:
print("This will print if bool_flag is False")
# Option D:
if bool_flag == False:
print("This will print if bool_flag is False")
# Option E (per @CharlesDuffy):
match flag_bool:
case False:
print("This will print if bool_flag is False")
- Как правильно проверить ложь?
- Как в Python проверить, имеет ли переменная значение None, True или False
- Есть ли разница между «== False» и «is not» при проверке для пустой строки?
- Почему сравнение строк с использованием '==' или 'is' иногда дает другой результат?
- Есть ли разница между "==" и "is"?
- https://stackoverflow.com/a/37104262 /22396214
- https://stackoverflow.com/a /2021257/22396214
Подробнее здесь: https://stackoverflow.com/questions/784 ... e-vs-false