Why doesn’t this code work? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why doesn’t this code work?

Hi all, Can someone please explain why this code doesn’t work? items = [] n = int(input()) while True: if n > 0: items.append(n) print(items) else: break Thank you!

23rd Jul 2021, 4:55 AM
adele
11 Answers
+ 5
adele Loop will work till infinite because you are not decrementing n so if condition will be always True and every time n will be append in items. There is also Indentation problem in your code. Your code should be like this: items = [] n = int(input()) while True: if n > 0: items.append(n) print(items) n = n - 1 else: break
23rd Jul 2021, 5:08 AM
A͢J
A͢J - avatar
+ 1
items = [] n = int(input()) while True: if n > 0: items.append(n) print(items) n -= 1 # helps avoid infinite loops else: break
23rd Jul 2021, 5:10 AM
Rohit Kh
Rohit Kh - avatar
+ 1
adele items = [] n = int(input()) while n > 0: items.append(n) print(items) n -= 1
23rd Jul 2021, 6:20 PM
Amin Latm
Amin Latm - avatar
0
You can also put the input statement in the loop if you want to determine what input goes into the list. But this wouldn't work on SoloLearn, you need an interactive environment. https://code.sololearn.com/c2QYzO8mlS3t/?ref=app
23rd Jul 2021, 7:00 AM
Baribor Saturday
Baribor Saturday - avatar
0
items = [] n = int(input()) i = 0 while i < n: items.append(n) print(items) i += 1
23rd Jul 2021, 10:23 AM
Amin Latm
Amin Latm - avatar
23rd Jul 2021, 4:55 PM
adele
0
RKK can you please explain hope the logic works with n-=1?
23rd Jul 2021, 4:56 PM
adele
0
✔✅Barry🔧 , how do you mean by Sololearn isn’t an interactive environment?
23rd Jul 2021, 5:02 PM
adele
0
This is the problem and the expected output. However, i couldnt do it with any of the solutions above. Please help. The given code uses an infinite loop to continuously take user input. During each iteration, the user input is added to the items list. Change the code to end the loop when the user enters 0. Output the resulted list after the while loop ends. Sample Input 1 2 3 0 Sample Output [1, 2, 3]
23rd Jul 2021, 5:09 PM
adele
0
adele I just modified my code to do that. Check it out https://code.sololearn.com/c2QYzO8mlS3t/?ref=app
23rd Jul 2021, 5:17 PM
Baribor Saturday
Baribor Saturday - avatar
0
Thank you
24th Jul 2021, 12:10 AM
adele