Home > Blockchain >  Input a random integer in one line then print it from right to left in a separate line using loops i
Input a random integer in one line then print it from right to left in a separate line using loops i

Time:10-27

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
  • Related