select = input("Enter what you would like to do (enter 'x' to exit): ")
functions = {"c": calculator, "a": addsubtract, "s": squareroot,
"p": power, "n": arrange, "f": factorial} # storing break or return result in "Invalid Syntax" in the dictionary
#currently I'm doing this:
if select != "x":
functions[select]()
else:
return
我正在尝试最小化代码,并且能够通过将函数存储在字典中来实现;我想知道是否有一种解决方法/类似方法,以防万一使用字典无法实现。
答案 0 :(得分:1)
你不能:
def r():
return 1
def print_hello():
print("HelloWorld")
l = [print_hello, print_hello, print_hello, r, None]
if __name__ == '__main__':
for i in range(10):
print(i, end='')
l[i]()
$ python3 test.py
> 0HelloWorld
> 1HelloWorld
> 2HelloWorld
> 34Traceback (most recent call last):
> File "test.py", line 14, in <module>
> l[i]()
> TypeError: 'NoneType' object is not callable
将函数存储在字典中并不是一个好主意: https://www.python.org/dev/peps/pep-0020/
Flat比嵌套好。