开发者

Howcome a string type variable is considered as boolean in Python?

In the code below:

def modify_note(self):
    id = input("Enter a note id: ")
    memo = input("Enter a memo: ")
    tags = input("Enter tags: ")
    if memo:
       self.notebook.modify_memo(id, memo)
    if tags:
       self.not开发者_JAVA百科ebook.modify_tags(id, tags)

memo and tags are string type variables. How can you write them after if, does python regard them as boolean here?


Every object in Python has a truth value. Strings are True if they are non-empty.


The if memo and if tags statements are checking the truthiness of the memo and tags variables.

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  • None
  • False
  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.
  • any empty sequence, for example, '', (), [].
  • any empty mapping, for example, {}.
  • instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False.

All other values are considered true — so objects of many types are always true.


It all depends on Python's version of truthiness

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜