Home > database >  Reverse printing of input numbers after zero is received
Reverse printing of input numbers after zero is received

Time:08-01

In this code, I want the user to enter an integer, and until zero is entered, I receive input from the user. After receiving the number zero, I print the entered numbers except zero in the reverse order of their insertion.

I have two problems:
-One is how to not print the number zero in the output of the program
-And the second is how to correctly add the entry before the while loop to the num list

inp = int(input())
num = []
num.append(inp)
while inp > 0:
    out = int(input())
    num.append(out)
    if out == 0:
        for i in num[::-1]:
            print(i)
Sample input :   
3  
4  
7  
4  
9  
0
Sample output :  
9  
4  
7  
4  
3
But my output is like this :  
0  
9  
4  
7  
4  
3

CodePudding user response:

Just add the condition that checks if the input is 0 before appending the value to the list

inp = int(input())
num = []
num.append(inp)
while inp > 0:
    out = int(input())
    if out == 0:
        for i in num[::-1]:
            print(i)

    num.append(out)

But

even the first input can be 0, so modify your code to this

num = []
out = 1

while out > 0:
    out = int(input())

    if out == 0:
        for i in num[::-1]:
            print(i)
    else:
        num.append(out)

CodePudding user response:

Since you're using the break and while statement you can use a infinite loop and break it only when inp is zero otherwise keep adding the inp to the list.

And in the end print the numbers in the reverse order as you're already doing.

This is more simple because:

  • You read if inp == 0: break you automatically see that the while stops looping (rather of being forced to read a nested for inside a if).

  • You split your code in to: collect numbers and print numbers (while and for statements).

  • You no longer need to repeat your int(input(...)) call (before while and when whiling since everything is done inside the loop).

num = []

while True:
    inp = int(input())
    if inp == 0:
        break
    num.append(inp)

for i in num[::-1]:
    print(i)
  • Related