停止功能运行两次

问题描述

作为评估程序的一部分,我必须包含网络设备的库存管理功能。具体来说 - 添加设备、删除设备、更改数量和列出所有设备。目前停留在“添加设备”上。当它运行时,会提示用户提供 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

解决方法

你可以 return add_new_device()

而不仅仅是: add_new_device()

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...