zoukankan      html  css  js  c++  java
  • 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]() # 当对一函数引用但不加()时,只是引用,并不执行,所以这里加上()如果有参数,也可以传参数
  • 相关阅读:
    第十周学习进度条
    第九周学习进度条
    Runner站立会议08
    Runner站立会议07
    构建之法阅读笔记02
    Runner站立会议04
    学习进度条
    Runner站立会议01
    进度条
    返回一个一维整数数组中最大子数组的和
  • 原文地址:https://www.cnblogs.com/Andy963/p/5234843.html
Copyright © 2011-2022 走看看