Python Glossary Русский

all Python 3Loopsconstruct

Processing the digits of a number

practice

The pattern for walking the digits of a number: convert it to a string, or divide by 10 repeatedly. Used for digit sum, product, counting and largest-digit problems.

Syntax

for d in str(abs(n)): | while n > 0: d = n % 10; n //= 10

The while n > 0 version never enters the body when n = 0 and yields nothing — zero has to be special-cased. Negative numbers need abs(): str(n) puts a '-' in the string that int(d) chokes on, and % and // behave counterintuitively on negatives.

Examples

n = 12345
print(sum(int(d) for d in str(n)))  # → 15 — сумма цифр
print(len(str(abs(n))))  # → 5 — количество цифр
print(max(int(d) for d in str(n)))  # → 5 — наибольшая цифра
n = 12345
product = 1
for d in str(n):
    product *= int(d)
print(product)  # → 120 — произведение цифр
# Без перевода в строку: divmod
n, total = 12345, 0
while n:
    n, d = divmod(n, 10)
    total += d
print(total)  # → 15
print(int(str(4321)[::-1]))  # → 1234 — перевёрнутое число

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy