Home > Enterprise >  How could I call hundreds in python?
How could I call hundreds in python?

Time:10-18

When I split certain numbers into "ones" and "tens" in python, like that (98) we code >>>

num = 98
ones = num % 10 
tens = num // 10 
print(ones) = 8 
print(tens) = 9

So, if I have 3 digits number like 321 (based on the code have shown previously) the ones will be 1, tens = 32 . and I need python to execute 3 and 2 separately !!

CodePudding user response:

First, you can use divmod:

tens, ones = divmod(98, 10)
tens
# 9
ones
# 8

Second, you could write a generic function to get all digits regardless of magnitude:

def digs(n):
    while n:
        n, dig = divmod(n, 10)
        yield dig

ones, tens, hundreds, *_ = digs(321)

It will always produce all digits starting with ones:

[*digs(12345)]
# [5, 4, 3, 2, 1]

Of course, the simplest is just string conversion:

[*map(int, str(12345))]
# [1, 2, 3, 4, 5]

CodePudding user response:

You can write a function doing the modulo operations, put those in a list, make the division by then and repeat until the end, reverse the list:

def split_number(number):
    result = []
    while number != 0:
        result.append(number % 10)
        number = number // 10
    result.reverse()
    return result
split_number(12345)
[1, 2, 3, 4, 5]

CodePudding user response:

like this :

321 / 100
3.21
>>> int(3.21)
3

But you have already made a better thing for 10 why you don't make it for 100?

  • Related