Write the code to end the loop when the user enters 0 and the output the resulted list after the while loop ends. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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

17th Oct 2020, 7:48 AM
Rahul Prasad
Rahul Prasad - avatar
8 Answers
+ 4
items = [ ] while True: n = int ( input ( ) ) if n == 0: print ( items ) break items.append ( n )
17th Oct 2020, 7:52 AM
abhinav
abhinav - avatar
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
17th Oct 2020, 7:54 AM
Slick
Slick - avatar
0
Abhinav Anand this is working but can you explain from if n==0....
17th Oct 2020, 8:21 AM
Rahul Prasad
Rahul Prasad - avatar
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.
17th Oct 2020, 8:24 AM
Slick
Slick - avatar
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 ).
17th Oct 2020, 8:37 AM
abhinav
abhinav - avatar
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 )
25th Jan 2021, 1:15 PM
Justin Evans
Justin Evans - avatar
0
#Also user_list = [] while True: user_input = int(input()) if user_input == 0: break user_list.append(user_input) print(user_list)
18th Feb 2022, 8:23 PM
Matumbai Binale
Matumbai Binale - avatar
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)
24th Mar 2022, 11:23 AM
Rushikesh Jogdand
Rushikesh Jogdand - avatar