【问题标题】:Terenary operator not working with conditional assignment [duplicate]三元运算符不适用于条件赋值[重复]
【发布时间】:2021-08-27 13:31:51
【问题描述】:

我试着写了

age = 22
message = "Eligible" if age>=22 else message = "not eligible"
print(message)

以上代码因错误而失败

SyntaxError: cannot assign to conditional expression

为什么这不起作用?

【问题讨论】:

  • 三元运算符对表达式进行操作,而不是像赋值这样的任意语句。你想写message = "Eligible" if age>=22 else "not eligible"

标签: python python-3.x


【解决方案1】:

你只需要去掉else语句后的message =

message = "Eligible" if age>=22 else "not eligible"

三元运算符的结构如下:

variable = [value on_true] if [expression] else [value on_false]  

【讨论】:

  • 非常感谢
猜你喜欢
  • 2011-03-06
  • 2017-07-16
  • 1970-01-01
  • 2018-08-14
  • 2019-03-31
  • 2013-08-13
  • 2013-06-28
相关资源
最近更新 更多