How to find the numbers in the thousands, hundreds, tens, and ones place in PYTHON for an input number? For example: 256 has 6 ones, 5 tens, etc

num = int(input("Please give me a number: "))
print(num)
thou = int((num // 1000))
print(thou)
hun = int((num // 100))
print(hun)
ten =int((num // 10))
print(ten)
one = int((num // 1))
print(one)

I tried this but it does not work and I'm stuck.


Solution 1:

You might want to try something like following:

def get_pos_nums(num):
    pos_nums = []
    while num != 0:
        pos_nums.append(num % 10)
        num = num // 10
    return pos_nums

And call this method as following.

>>> get_pos_nums(9876)
[6, 7, 8, 9]

The 0th index will contain the units, 1st index will contain tens, 2nd index will contain hundreds and so on...

This function will fail with negative numbers. I leave the handling of negative numbers for you to figure out as an exercise.

Solution 2:

Like this?

a = str(input('Please give me a number: '))

for i in a[::-1]:
    print(i)

Demo:

Please give me a number: 1324
4
2
3
1

So the first number is ones, next is tens, etc.