'How could I call hundreds in python?
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 !!
Solution 1:[1]
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]
Solution 2:[2]
This is a generic Python code to split the digits (ones, tens, hundreds, and so on)
num = int(input())
count = 0
while (num != 0):
mod = num % 10
div = num // 10
count = count + 1
print ("The number in position", count, " is ", mod)
num = div
This code works by repeated division.
Solution 3:[3]
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]
Solution 4:[4]
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?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | Mandraenke |
Solution 4 |