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
orwhile
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 orbool
valueFalse
.All other values are considered true — so objects of many types are always true.
It all depends on Python's version of truthiness
精彩评论