Python evaluates 0 as False(Python 将 0 评估为 False)

本文介绍了Python 将 0 评估为 False的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 控制台中:

In the Python console:

>>> a = 0
>>> if a:
...   print "L"
... 
>>> a = 1
>>> if a:
...   print "L"
... 
L
>>> a = 2
>>> if a:
...   print "L"
... 
L

为什么会这样?

推荐答案

在Python中,boolint的子类,False值为 0;即使值没有在 if 语句(它们是)中隐式转换为 boolFalse == 0 也是 true.

In Python, bool is a subclass of int, and False has the value 0; even if values weren't implicitly cast to bool in an if statement (which they are), False == 0 is true.

这篇关于Python 将 0 评估为 False的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!