【问题标题】:Why are complex arithmetic operation not allowed in the while condition in python [duplicate]python - 为什么在python中的while条件中不允许进行复杂的算术运算[重复]
【发布时间】:2018-10-10 15:42:39
【问题描述】:

此函数查找数字中的位数

def getNumOfDigits(i):
    num = i
    count = 1
    num = num // 10
    while num != 0:
        count += 1
        num //= 10
    return count

如果我尝试修改 while 条件以将 num 除以 10 并检查它是否不等于 0,则会引发语法错误。为什么在python中会这样?

def getNumOfDigits(i):
num = i
count = 1
while (num //= 10)!= 0:
    count += 1
return count

【问题讨论】:

    标签: python


    【解决方案1】:

    num //= 10 等赋值是语句,不能成为表达式的一部分。

    为什么在 python 中会这样?

    最近决定在某些情况下应该允许在表达式中赋值,这引起了巨大的争议,请参阅this article了解更多信息。

    【讨论】:

    • 但你可以说pep-0572
    • 感谢您提供指向这篇非常有趣的文章的链接!
    猜你喜欢
    • 2011-05-07
    • 2013-01-08
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 2019-10-02
    • 1970-01-01
    相关资源
    最近更新 更多