• python 字典实现类似c的switch case


     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]() # 当对一函数引用但不加()时,只是引用,并不执行,所以这里加上()如果有参数,也可以传参数
  • 相关阅读:
    数据库(六)
    数据库(五)
    数据库(四)
    数据库(三)
    数据库(二)
    数据库
    函数 枚举和递归
    数据类型(四) 集合
    数据库基础
    特殊集合 结构体
  • 原文地址:https://www.cnblogs.com/Andy963/p/5234843.html
Copyright © 2020-2023  润新知