0

This function finds the number of digits in a number

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

If I try to modify the while condition to divide num by 10 and check if it is not equal to 0 it throws up a syntax error. Why is this so in python?

def getNumOfDigits(i):
num = i
count = 1
while (num //= 10)!= 0:
    count += 1
return count
Cœur
  • 37,241
  • 25
  • 195
  • 267
gopal
  • 39
  • 6

1 Answers1

5

Assignment such as num //= 10 is a statement and cannot be part of an expression.

Why is this so in python?

Recently it was decided that assignment should be allowed in expressions in certain situations and this caused a huge controversy, see this article for more.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89