1 #python 字典实现类似c的switch 2 3 def print_hi(): 4 print('hi') 5 6 def print_hello(): 7 print('hello') 8 9 def print_goodbye():10 print('goodbye')11 12 choice = int(input('please input your choice:')) # 例子,不考虑输入错误的情况13 14 # if ... elif 实现15 if choice ==1:16 print_hi()17 elif choice ==2:18 print_hello()19 elif choice ==3:20 print_goodbye()21 22 # 字典实现23 choice_dict = {1:print_hi, 2:print_hello, 3:print_goodbye} # 这里只是引用函数,如果写成print_hi()这种形式,则一运行程序,所有选择都会执行一遍24 # 替代方案是:1:lamba:print_hi()这种形式25 choice = int(input('please input your choice:'))26 27 choice_dict[choice]() # 当对一函数引用但不加()时,只是引用,并不执行,所以这里加上()如果有参数,也可以传参数
posted on 2016-03-02 14:25 阅读( ...) 评论( ...)