【问题标题】:Syntax Error in Inline if … else Syntax in Python内联中的语法错误 if ... else Python 中的语法
【发布时间】:2018-08-03 09:27:51
【问题描述】:

语法到底有什么问题,为什么在下面的代码中? 我已经计算了括号以及其他内容,但无法弄清楚。

c = ""
 print("Yes") if c else print("No")

注意:它会给出如下所示的语法错误:

print("Yes") if c else print("No")
                            ^
SyntaxError: invalid syntax

【问题讨论】:

  • 它对我有用....看看你的缩进
  • @B001ᛦ 它是如何工作的?
  • print 是 python 2 中的语句。不能在条件中使用语句。
  • 在 Python 2 中 print "Yes" if c else "No"

标签: python python-2.7 if-statement syntax-error


【解决方案1】:

这是因为 print 函数在 python2 和 python3 中的行为不同:
同时在 python3 中,您的代码运行良好,在 python2 中它会引发错误。
这是因为在 python2 中,print 实际上是 statement 而不是函数; here你可以找到更深入的QA关于函数和语句的区别。

顺便说一句,你可以解决你从future导入python3打印功能的问题:

from __future__ import print_function

c = ""

print("Yes") if c else print("No")

输出:

No

【讨论】:

    猜你喜欢
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 2018-12-22
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多