【发布时间】:2021-05-10 06:19:50
【问题描述】:
作为评估程序的一部分,我必须包含网络设备的库存管理功能。特别是 - 添加设备、删除设备、更改数量和列出所有设备。目前停留在“添加设备”上。运行时,提示用户提供 3 个输入:
- 设备键(例如路由器的“R” - 稍后使用,以便用户可以轻松调用对象)
- 设备名称
- 设备数量
这些存储在字典数组中。在函数 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
【问题讨论】:
-
代替递归调用
add_new_device()你可以return add_new_device -
您实际上可以将代码包装在
Truewhile 循环中并返回值或在循环内再次要求提示 -
我应该在输入之前插入
while True:吗? -
@CunnyFunt 可能是函数的开头,然后在您希望函数重复的地方键入
continue。当代码最终到达那里时,while 循环只会在最终返回调用时中断