“字符串"的逻辑值是什么?在 Python 中? [英] What's the logical value of "string" in Python?
问题描述
我错误地用 Python 编写了这段代码:
I erroneously wrote this code in Python:
name = input("what is your name?")
if name == "Kamran" or "Samaneh":
print("That is a nice name")
else:
print("You have a boring name ;)")
即使输入既不是Kamran"也不是Samaneh",它总是会打印出那是个好名字".
It always prints out "That is a nice name" even when the input is neither "Kamran" nor "Samaneh".
我说它认为Samaneh"是真的是对的吗?为什么?
Am I correct in saying that it considers "Samaneh" as a true? Why?
顺便说一下,我已经注意到我的错误了.正确的形式是:
By the way, I already noticed my mistake. The correct form is:
if name == "Kamran" or name == "Samaneh":
推荐答案
Python(和大多数其他语言)中的任何非空字符串都是真的,所有非零数字和非空列表、字典、集合和元组也是如此.1
Any non empty string in Python (and most other languages) is true as are all non-zero numbers and non-empty lists, dictionaries, sets and tuples.1
做你想做的更好的方法是:
A nicer way to do what you want is:
name = input("what is your name?")
if name in ("Kamran", "Samaneh"):
print("That is a nice name")
else:
print("You have a boring name ;)")
这将创建一个包含您想要的名称的元组并执行成员资格测试.
This creates a tuple containing the names that you want and performs a membership test.
1 正如 delnan 在评论中指出的,这适用于所有写得好的集合.也就是说,如果你实现了自定义的集合类,请确保它为空时为false.
1 As delnan points out in the comments, this applies to all well written collections. That is, if you implement a custom collection class, make sure that it is false when it's empty.
这篇关于“字符串"的逻辑值是什么?在 Python 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!