Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading