Python:我如何(可以)在字典中存储“return”或“break”?

时间:2016-05-25 13:13:15

标签: python-3.x dictionary return break

    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

我正在尝试最小化代码,并且能够通过将函数存储在字典中来实现;我想知道是否有一种解决方法/类似方法,以防万一使用字典无法实现。

1 个答案:

答案 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比嵌套好。