Reverse printing of input numbers after zero is received

Question:

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
Asked By: farzaneh taheri

||

Answers:

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)
Answered By: Geeky Quentin

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)
Answered By: Alex Rintt
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.