你的代码过于复杂了。
def fun(name=None):
names = ["tom", "nick", "juli"]
if name is None:
return [[name] for name in names]
if name in names:
return [name]
raise Exception(f"{name} 不在已知名字列表中")
print(fun("nick"))
print(fun())
print(fun("banana"))
输出:
['nick']
[['tom'], ['nick'], ['juli']]
Traceback (most recent call last):
File "/Users/CtrlZ/Python/Jan05.py", line 41, in <module>
print(fun("banana"))
^^^^^^^^^^^^^
File "/Users/CtrlZ/Python/Jan05.py", line 37, in fun
raise Exception(f"{name} is not in list of known names")
Exception: banana 不在已知名字列表中
采用这种模式,在向names
列表添加名字时无需编写额外的if/else代码,操作更为简单。