How to return floating values using floor division

45 Views Asked by At

In Python 3, I want to return the units place of an integer value, then tens, then hundreds and so on. Suppose I have an integer 456, first I want to return 6, then 5 then 4. Is there any way? I tried floor division and for loop but didn't work.

2

There are 2 best solutions below

0
On

Write a generator if you want to retrieve digits in different places of your code based on requirement as follows.

If you are not much familiar with Python's generator, have a quick look at https://www.programiz.com/python-programming/generator.

» Here get_digits() is a generator.

def get_digits(n):
    while str(n):
        yield n % 10

        n = n // 10
        if not n:
            break

digit = get_digits(1729)

print(next(digit)) # 9
print(next(digit)) # 2
print(next(digit)) # 7
print(next(digit)) # 1

» If you wish to iterate over digits, you can also do so as follows.

for digit in get_digits(74831965):
    print(digit)

# 5
# 6
# 9
# 1
# 3
# 8
# 4
# 7

» Quick overview about its usage (On Python3's Interactive terminal).

>>> def letter(name):
...     for ch in name:
...         yield ch
... 
>>> 
>>> char = letter("RISHIKESH")
>>> 
>>> next(char)
'R'
>>> 
>>> "Second letter is my name is: " + next(char)
'Second letter is my name is: I'
>>> 
>>> "3rd one: " + next(char)
'3rd one: S'
>>> 
>>> next(char)
'H'
>>> 
0
On

If you look at the list of basic operators from the documentation, for example here,

Operator    Description     Example
% Modulus   Divides left hand operand by right hand operand and returns remainder   b % a = 1
//  Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity):    9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0

With that knowledge, you can get what you want as follows:

In [1]: a = 456 

In [2]: a % 10 
Out[2]: 6

In [3]: (a % 100) // 10 
Out[3]: 5

In [4]: a // 100 
Out[4]: 4