How to convert number 1 to a Boolean in python

一个人想着一个人 提交于 2020-01-03 13:09:33

问题


I have seen similar questions asked, but none have answered my question. I am relatively new to python, and have no idea what i'm doing.


回答1:


Use:

>>> bool(1)
True
>>> bool(0)
False
>>> int(bool(1))
1
>>> int(bool(0))
0

Can convert back too.




回答2:


Unless you don't want to explicitly use Boolean type variable you don't need to. Python accepts it as True in many expression:

print(True == 1)
print(False == 0)

Out:

True
True

In other cases you can use bool(1) of course.

print(bool(1))
print(bool(0))

Out:

True
False



回答3:


Only the following values will return False when passed as a parameter to bool()

  • None
  • False
  • Zero of any numeric type. For example, 0, 0.0, 0j
  • Empty sequence. For example, (), [], ''.
  • Empty mapping. For example, {}
  • objects of Classes which has bool() or len() method which returns 0 or False

Everything else returns True

Source1 Source2




回答4:


Very simple:

bool(1)

Here are a few scenarios, to show:

print(bool(1))

Will return: True

print(bool(0))

Will return: False



来源:https://stackoverflow.com/questions/53218570/how-to-convert-number-1-to-a-boolean-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!