DataScience
DataScience

Reputation: 21

Printing digits of an integer in order in Python

I want to print the digits of an integer in order, and I don't want to convert to string. I was trying to find the number of digits in given integer input and then divide the number to 10 ** (count-1), so for example 1234 becomes 1.234 and I can print out the "1". now when I want to move to second digit it gets confusing. Here is my code so far: Note: Please consider that I can only work with integers and I am not allowed to use string and string operations.

def get_number():
    while True:
        try:
            a = int(input("Enter a number: "))
            return a
        except:
            print("\nInvalid input. Try again. ")

def digit_counter(a):
    count=0
    while a > 0:
        count = count+1
        a = a // 10
    return count

def digit_printer(a, count):
    while a != 0:
        print (a // (10 ** (count-1)))
        a = a // 10

a = get_number()
count = digit_counter(a)
digit_printer(a, count)

I want the output for an integer like 1234 as below:

1
2
3
4

Upvotes: 0

Views: 1701

Answers (2)

Kelly Bundy
Kelly Bundy

Reputation: 27588

Finding the largest power of 10 needed, then going back down:

n = 1234

d = 1
while d * 10 <= n:
    d *= 10
while d:
    print(n // d % 10)
    d //= 10

Upvotes: 3

Christian Sloper
Christian Sloper

Reputation: 7510

Using modulo to collect the digits in reversed order and then print them out:

n = 1234
digits = []
while n > 0:
    digits.append(n%10)
    n //=10

for i in reversed(digits):
    print(i)

Recursive tricks:

def rec(n):
    if n > 0:
       rec(n//10)
       print(n%10)

rec(1234)

Upvotes: 3

Related Questions