Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reverse printing of input numbers after zero is received

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading