Home > front end >  My Python program has to add or remove an item in the end of a list. The item that is added must be
My Python program has to add or remove an item in the end of a list. The item that is added must be

Time:11-18

My code doesn't work as it should. After my input - it prints out [1, 2, 4] instead [1, 2, 3]. I think there is some problem with i-value, but I don't get how to fix it. Please help me with your advise!

list = []
i = 1

while True:
    print((f"Now {list}"))
    
    n = input("add or remove:")
           
    if n == " ":
        list.append(i)
        i =1

    if n == "-":
        list.pop(-1)

CodePudding user response:

Put a decrementor/decrease the number under the "-" condition -

if n == "-":
    list.pop() # This is equivalent to .pop(-1) - Removes last item

    if i != 0: # If list is empty then don't remove
        i -= 1 # This will reduce the number and give expected output

CodePudding user response:

Here is the code:

list = [] i = 0

while True: print((f"Now {list}"))

n = input("add or remove:")
       
if n == " ":
    i =1
    list.append(i)

if n == "-":
    i-=1
    list.pop()

CodePudding user response:

While the other answers explain the problem with the i I'd like to present an approach that doesn't need this variable at all. The question states "The item that is added must be one greater than the last item in the list". So we get the value of the last item, increase it by one and append this increased value to the list. If the list is empty we use a default value of 1.

data = []
while True:
    print(f"Now {data}")
    n = input("add or remove:")
    if n == " ":
        new_value = data[-1]   1 if data else 1
        data.append(new_value)
    elif n == "-":
        data.pop()

CodePudding user response:

Do you try to replace the second "if" by "elif" ?

  • Related