简体   繁体   中英

My Python program has to add or remove an item in the end of a list. The item that is added must be one greater than the last item in the list

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)

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

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()

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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM