首页 > 解决方案 > 停止函数运行两次

问题描述

作为评估程序的一部分,我必须包括网络设备的库存管理功能。特别是 - 添加设备、删除设备、更改数量和列出所有设备。目前停留在“添加设备”上。运行时,系统会提示用户提供 3 个输入:

  1. 设备键(例如路由器的“R” - 稍后使用,以便用户可以轻松调用对象)
  2. 设备名称
  3. 设备数量

这些存储在字典数组中。在函数add_new_device()中,我在语句中包含了一个错误检查if- 因此,如果用户要输入现有的密钥或设备名称,他们会收到一条消息提示,然后再次调用该函数以重新启动该add_new_device()函数。

问题: 假设使用输入“R”作为设备密钥(它已经存在)。消息将提示,功能将重新启动。在完成键、名称和数量的输入之后,来自先前调用的设备名称和数量将完成执行。

如何终止当前的函数调用,并启动函数调用的新实例?

def add_new_device():

    print("\n––––––––––––––––––––––––––––––––––––––––––––––––––––––––––")
    print("\n  > MAIN MENU > SHOW OR EDIT INVENTORY > ADD NEW DEVICE")

    new_device = {}

    print ("\nPlease enter a key for your device - e.g.  "R" for Router")
    new_devkey = input("\n\n Device key:  ")
    new_device["dev_key"] = new_devkey
    if any(x["dev_key"] == new_devkey for x in devices_all):
        print("\n––––––––––––––––––––––––––––––––––––––––––––––––––––––––––")
        print("\n               DEVICE KEY ALREADY EXISTS!")
        print("              PLEASE ASSIGN A DIFFERENT KEY")
        time.sleep(1)
        ### KILL CURRENT FUNCTION CALL HERE ###
        add_new_device()


    new_devname = input(" Device name:  ") 
    new_device["dev_name"] = new_devname
    if any(y["dev_name"] == new_devname for y in devices_all):

        print("\n––––––––––––––––––––––––––––––––––––––––––––––––––––––––––")
        print("\n              DEVICE NAME ALREADY EXISTS!")
        print("             PLEASE ASSIGN A DIFFERENT NAME")
        time.sleep(1)
        ### KILL CURRENT FUNCTION CALL HERE ###
        add_new_device()

        
    new_device["dev_quantity"] = input(" Device quantity:  ")

    devices_all.append(new_device)
    
    print("\n––––––––––––––––––––––––––––––––––––––––––––––––––––––––––")
    print("\n              SUCCESSFULLY ADDED NEW DEVICE")
    print("\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . ")

    return new_device

标签: pythonfunctioncallkill

解决方案


你可以做 return add_new_device()

而不仅仅是: add_new_device()


推荐阅读