0
Write the code to end the loop when the user enters 0 and the output the resulted list after the while loop ends.
please help me to do this.... i tried it.... items =[ ] while True: n = int(input()) items.append(n) if n>0: print("Breaking") break else : print(items ) but its not working
8 Answers
+ 4
items = [ ]
while True:
n = int ( input ( ) )
if n == 0:
print ( items )
break
items.append ( n )
0
you append n before the check, it should be after.
if n > 0 should be if n == 0.
you can then slide the print(items) statement in under the check for 0
0
Abhinav Anand
this is working
but can you explain from if n==0....
0
he takes a number as input, then 1 of 2 things happen.
if the number is 0, he prints the full list and exits the loop.
if the number is anything but zero, it will add the number to the list and ask for another number and do it all over again.
0
when n == 0 it prints the list. break statement terminates the loop and anything following it in loop's the block (code inside the loop's indentation ).
As a result items.append ( n ) is not executed after break ( when n == 0 ).
0
seems to be a bug with the spacing, well worked out a b h i n a v,
I would add the following modification to the Python code
items = [ ]
while True:
n = int ( input ( ) )
if n == 0:
print ( items )
break
else:
items.append ( n )
0
#Also
user_list = []
while True:
user_input = int(input())
if user_input == 0:
break
user_list.append(user_input)
print(user_list)
0
A solution in app shown print at last line of code, I lost my half hour.
It's actually
If statement - - >break statement - - >statement for continuous loop.
If it breaks the condition then exit the paragraph and end the program by printing (items)