 Why doesn’t this code work? | Sololearn: Learn to code for FREE!

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!

+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

+1

items = [] n = int(input()) while True: if n > 0: items.append(n) print(items) n -= 1 # helps avoid infinite loops else: break

+1

adele items = [] n = int(input()) while n > 0: items.append(n) print(items) n -= 1

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

0

items = [] n = int(input()) i = 0 while i < n: items.append(n) print(items) i += 1

0

Thank you RKK ✔✅Barry🔧 Amin Latm

0

RKK can you please explain hope the logic works with n-=1?

0

✔✅Barry🔧 , how do you mean by Sololearn isn’t an interactive environment?

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]

0

adele I just modified my code to do that. Check it out https://code.sololearn.com/c2QYzO8mlS3t/?ref=app