What's the logical value of “string” in Python?

霸气de小男生 提交于 2019-12-17 20:34:52

问题


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 ;)")

It always prints out "That is a nice name" even when the input is neither "Kamran" nor "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":

回答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 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.




回答2:


Besides the empty string '', strings will all evaluate to True (see this page for a full list of values of all types that evaluate to False. This follows the logic of many other programming languages (except some which also evaluate strings like '0', 'false', etc. to False). The exact decision of what to do is somewhat arbitrary, but the choice made can be explained as allowing the cast to be used as a simple way to test for empty (default, or unpopulated) strings.

You can always force a cast of any type to bool using the bool() function.

>>> bool('')
False
>>> bool('non-empty string')
True
>>> bool('0')
True
>>> bool('False')
True
>>> bool('false')
True



回答3:


http://docs.python.org/library/stdtypes.html#truth-value-testing

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




回答4:


In Python an empty string is considered False, True otherwise.

You could use the in operator:

if name in ("Kamran","Samaneh"):
    print("That is a nice name")
else:
    print("You have a boring name ;)")



回答5:


A non-empty string is True, yes. An empty one is False. This is super-handy.




回答6:


Evidently, it must be:

name = raw_input("what is your name?")

not

name = input("what is your name?")

.

What you wrote is like:

if (name == "Kamran" or "Samaneh")

Another good expression is:

if name == ("Kamran" or "Samaneh")

But I also prefer if name in ("Kamran" or "Samaneh") as already shown

.

By the way, it can be written:

print("That is a nice name" if raw_input("what is your name?") in ("Kamran","Samaneh")
      else "You have a boring name ;)")


来源:https://stackoverflow.com/questions/4531794/whats-the-logical-value-of-string-in-python

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