根据大小防止列表添加

时间:2017-09-07 23:50:53

标签: python python-3.x

我试图将grab命令限制为一次只允许列表中的4个项目以及dropedit命令。如果用户输入任意数量的无效数字项,我会尝试添加一条说invalid的邮件。

  def grab(item_list):
       item = input("Name: ")
       item_list.append(item)
       print(item + " was added.\n")


   def edit(item_list):
       pos = int(input("Number: "))    
       new_value = input("Updated name: ")
       item_list[pos-1] = new_value
       print("%s was updated" % (new_value))

   def drop(item_list):
       number = int(input("Number: "))
       item = item_list.pop(number-1)
       print(item + " was dropped.\n")
       print()

   def main():
       item_list = ["wooden staff","wizard hat","cloth shoes"]

1 个答案:

答案 0 :(得分:0)

   def grab(item_list):
       if len(item_list)==4:
           print('Cannot grab more than 4. Drop another item and try again')
           return
       item = input("Name: ")
       item_list.append(item)
       print(item + " was added.\n")


   def edit(item_list):
       pos = int(input("Number: "))
       if not (pos-1)in range(len(item_list)):
           print(str(pos) + ' not in list, try again')
           edit(item_list)
           return
       new_value = input("Updated name: ")
       item_list[pos-1] = new_value
       print("Updated item %d with new value %s" % (pos, new_value))

   def drop(item_list):
       number = int(input("Number: "))
       if not (number-1) in range(len(item_list)):
           print(str(number) + ' not in list, try again')
           drop(item_list)
           return
       item = item_list.pop(number-1)
       print(item + " was dropped.\n")
       print()