Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 891
Johan Avatar asked Feb 04 '26 16:02

Johan


1 Answers

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.

like image 197
Aaron S Avatar answered Feb 06 '26 07:02

Aaron S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!