【问题标题】:Value in "word" makes no difference to my if statement [duplicate]“单词”中的值对我的 if 语句没有影响[重复]
【发布时间】:2020-05-31 23:25:50
【问题描述】:

我在学习 python 的第 4 天,所以如果我遗漏了一些非常明显的东西,我提前道歉。

整个程序发布在下面。 word = input() 无论我在输入提示中输入什么,我的树函数都不会被调用。但是,如果我将:if word == 'Chris' or 'j': 更改为 if word == 'Chris':,它似乎可以工作。

def tree(pine):
    return 'Hello' + pine


def app():
    word = input()
    if word == 'Chris' or 'j':
        print('Welcome ' + word + ' it is nice today! ', end='')
        print('It is so sunny')
    else:
        print(tree('lplp'))



app()

【问题讨论】:

  • 像这样:if word == 'Chris' or word == 'j':
  • 你可能也想格式化你的字符串:print(f'Welcome {word} it is nice today!')
  • if word in {'Chris', 'j'}:
  • 另外,我对此不是 100% 确定,但您的代码始终正确的原因是,当您执行 if variable_name: 语句时,您是在询问 Python 所说的变量是否不是 None 或错误的。在这种情况下,字符串 'j' 始终是 not-None 非 False,因此您的语句将始终评估为 True,因此 else 语句将永远不会运行
  • @JuanC 不完全是,每种数据类型都有自己的 python bool 怪癖。在字符串的情况下,任何非空字符串都被评估为True

标签: python


【解决方案1】:

问题出在

    if word == 'Chris' or 'j':

如果我们分解此语句,您将评估两个条件:

  1. word == 'Chris'
  2. 'j'

所以 Python 是一门有趣的语言,因为几乎任何类型的对象都可以被评估为布尔值。这意味着当您检查 if 'j' 时,实际上会显示为 True 而不是某种错误,因为 Python 在幕后做了很多事情。

要解决此问题,您只需确保检查了word == "j"

只是为了让您入门,例如,以下是一些常见的 python 布尔值:

>>> bool("")
False
>>> bool("j")
True
>>> bool(0)
False
>>> bool(69)
True
>>> bool([])
False
>>> bool(["hello", "world"])
True
>>> class Foo:

    def __init__(self):
        self.x = "y"


>>> bool(Foo())
True
>>> bool(None)
False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 2016-03-08
    • 2021-06-10
    • 1970-01-01
    • 2012-11-14
    • 1970-01-01
    • 2021-07-10
    相关资源
    最近更新 更多