【发布时间】:2021-08-05 16:29:09
【问题描述】:
我已经遵循了许多示例,说明如何在 Python 中创建字典来代替 switch-case 语句,但由于某种原因,我的代码似乎无法正常工作。函数 ViewCommands,当输入“viewCommands”(作为命令)时,它应该像在脚本开头那样执行,但没有被执行。
ViewCommands()
while True:
print()
print('?>> What command would you like to execute?:')
command = input()
print('>>> Executing command: ', command)
switcher = {
'viewCommands': ViewCommands,
'terminate': Terminate,
'viewSentences': ViewSentences,
'addSentences': AddSentences
}
case = switcher.get(command, '!');
if case == '!': print('!>> INVALID INPUT - NOT AN OPTION')
当我为每个引用添加括号时......就像这样:
ViewCommands()
while True:
print()
print('?>> What command would you like to execute?:')
command = input()
print('>>> Executing command: ', command)
switcher = {
'viewCommands': ViewCommands(),
'terminate': Terminate(),
'viewSentences': ViewSentences(),
'addSentences': AddSentences()
}
case = switcher.get(command, '!');
if case == '!': print('!>> INVALID INPUT - NOT AN OPTION')
...它确实按预期调用,但随后我遇到了一个错误,即 Terminate 被意外调用,尽管它不应该在字典查询中被引用。
有人知道我为什么会遇到这个问题吗?任何建议将不胜感激,并提前感谢!
【问题讨论】:
-
在第一个代码块中,函数没有被调用,因为你从不调用它。您认为哪段代码实际上会调用该函数?