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]() # 当对一函数引用但不加()时,只是引用,并不执行,所以这里加上()如果有参数,也可以传参数
  • 相关阅读:
    nginx 启动相关的
    爬取豆瓣读书/文件存储数据/数据库存储数据
    python Web 开发三剑客比较
    scrapy
    爬虫自动登录抽屉
    组合搜索
    html瀑布流
    Ajax上传文件/文件预览
    Form组件
    django分页
  • 原文地址:https://www.cnblogs.com/Andy963/p/5234843.html
Copyright © 2011-2022 走看看