I'm trying to make a program that inputs random integers in a single line and the print them all it's digits in a separate line from right to left order using while loops. But when I try to execute my code it always adds a zero at the bottom. How can I remove it?
Here's my code:
i = int(input())
while i != 0:
a = int(i) % 10
print(a)
i = int(i) / 10
INPUT:
123
OUTPUT:
3
2
1
0 #NEED TO REMOVE ZERO
CodePudding user response:
found the problem. You see, you are trying to compare the float i to an integer. Therefore, even though your console prints out 0, the actual value of i is not 0.
Try this:
i = int(input())
while int(i) != 0:
a = int(i) % 10
print(a)
i = int(i) / 10
CodePudding user response:
Here you could just use a conditional statement:
i = int(input())
while int(i) != 0:
a = int(i) % 10
if a:
print(a)
i = int(i) / 10
CodePudding user response:
Instead of normal division operator(/), try using floor division (//) in the last line to avoid decimals.
i = int(input())
while i != 0:
a = int(i) % 10
print(a)
i = int(i) //10