【问题标题】:Python: "if A and B:" and "if B and A:"Python:\"如果 A 和 B:\" 和 \"如果 B 和 A:\"
【发布时间】:2022-10-01 01:20:30
【问题描述】:

代码一:

loveme = input(\'Enter Yes or No:\')
if loveme[0] == \'Y\' and len(loveme) > 0:
   print(\'Yes!\')

代码二:

loveme = input(\'Enter Yes or No:\')
if loveme[0] == \'Y\' and len(loveme) > 0:
   print(\'Yes!\')

很明显,一个是“如果 A 和 B”,另一个是“如果 B 和 A”。对我来说,A和B应该可以毫无问题地切换。但是,当我尝试对他们两个都输入 no response 时,第一个根本没有响应,但是第二个崩溃了。任何人都可以解释其背后的逻辑吗?

  • 2个代码是一样的。但我认为你的问题是因为short-circuiting(特别是注意#2)。

标签: python if-statement


【解决方案1】:

python check的方式是按照接收到的顺序来检查条件。如果您首先检查loveme[0] == 'Y' 而没有条目,python 会在不检查第二个条件的情况下生成错误。

【讨论】:

    猜你喜欢
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    • 2021-03-14
    • 2016-05-02
    相关资源
    最近更新 更多