The closest equivalent of your C/Java code in Python would be this:
total = 0
i = 0
while number > 0:
if i % 2 == 0:
total += number % 10
number //= 10
i += 1
This is not very elegant, as you have to rewrite the for (...;...;...)
loop with a while
and separate lines for initialization and increment. Note that his is close to what you have, but there are two important differences: First, the i += 1
should be at the end of the loop, as the third block of the for
is also executed after each iteration. Also note the //
for integer division in Python!
This just calculates the sum of all digits. The i % 2
part is irrelevant as the number //= 10
bit is only executed within that block, so it just makes the outer loop run twice as long. If that is indeed what you want, you could simplify it to this, without i
:
while number > 0:
total += number % 10
number //= 10
Or just this:
total = sum(map(int, str(number)))
If, however, you want to add every other digit (starting from the end), e.g. 6+4+2
for 123456
, then you have to move the /= 10
part to the outer loop (in the first version including i
), i.e. decrease the indentation in Python. The rest remains the same.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…