0

I am trying to create a function in which python must print each individual digit of the number in a different line. I have to deal with numbers and digits mathematically instead of strings. However as I initially approached it I approached it using the string method to have some grasp on where to begin. However the code I did works as I need it to only if the user inputs a group numbers that are separated by commas. I want for the user to input for example; (my_numbers(4523)):

4

5

2

3

Here is the code i've been working on:

def my_numbers():
    item = input('enter num:')
    result='\n'.join(item.split(','))
    print(result)
my_numbers()
mark122021
  • 61
  • 6

2 Answers2

0

Non string approach :

import math

def my_numbers():
    item = int(input('enter num: '))
    digits = [(item//(10**i))%10 for i in range(math.ceil(math.log(item, 10)), -1, -1)][bool(math.log(item,10)%1):]
    for d in digits:
        print(d)

See : Turn a single number into single digits Python

Charles Dupont
  • 995
  • 3
  • 9
0

You should also take into consideration negative numbers and 0. math.log unfortunately doesn't work on these kind of input. An alternative would be to use a while loop.

def my_numbers():
    item = int(input('enter num:'))
    result = []

    if item == 0:
        print(item)
    elif item < 0:
        item = -item
        print('-')

    while item > 0:
        # Extract last digit
        digit = item % 10
        result.insert(0, digit)
        # Remove last digit
        item = item // 10

    for digit in result:
        print(digit)

my_numbers()
AcidResin
  • 134
  • 2
  • 12