You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python while循环内使用赋值运算符触发SyntaxError,求问题排查

问题原因及修正方案

错误根源

你写的代码里,num //= 2 if not num%2 else num -= 1这一行违反了Python语法规则:

  • Python的三元条件表达式a if cond else b中,a和b必须是表达式(能产生返回值的代码片段)。
  • 而num -= 1是赋值语句,不是表达式,不能作为三元表达式的分支,因此触发SyntaxError。

修正方案

方案一:拆分条件判断(可读性最优)

直接用常规的if-else语句替代三元表达式,逻辑更清晰,也符合Python的语法要求:

class Solution:
    def numberOfSteps(self, num: int) -> int:
        step = 0
        while num != 0:
            if num % 2 == 0:
                num //= 2
            else:
                num -= 1
            step += 1
        return step

方案二:调整为合法的三元表达式写法

如果想保持一行赋值,可以把赋值操作统一放在左侧,右侧的三元表达式返回正确的计算值:

class Solution:
    def numberOfSteps(self, num: int) -> int:
        step = 0
        while num != 0:
            num = num // 2 if num % 2 == 0 else num - 1
            step += 1
        return step

内容的提问来源于stack exchange,提问作者syswraith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 11:38:13