Python分支结构(switch)操作简介

yipeiwu_com7年前Python基础

Python当中并无switch语句,本文研究的主要是通过字典实现switch语句的功能,具体如下。

switch语句用于编写多分支结构的程序,类似与if….elif….else语句。

switch语句表达的分支结构比if…elif…else语句表达的更清晰,代码的可读性更高

但是python并没有提供switch语句。

python可以通过字典实现switch语句的功能,实现方法分为两步:

首先,定义一个字典

其次,调用字典的get()获取相应的表达式。

计算器:

from __future__ import division
def jia(x,y):
 return x+y
def jian(x,y):
 return x-y
def cheng(x,y):
 return x*y
def chu(x,y):
 return x/y
def operator(x,o,y):
 if o=='+':
  print (jia(x,y))
 elif o=='-':
  print (jian(x,y))
 elif o=='*':
  print (cheng(x,y))
 elif o=='/':
  print (chu(x,y))
 else:
  pass
operator(2,'/',4)

用字典来实现switch操作

from __future__ import division
def jia(x,y):
 return x+y
def jian(x,y):
 return x-y
def cheng(x,y):
 return x*y
def chu(x,y):
 return x/y
operator={"+":jia,"-":jian,"*":cheng,"/":chu}
print(operator["+"](3,2)) #operator["+"]等同于jia
print (jia(3,2)) #operator["+"](3,2)等同于jia(3,2)

运行结果:
5
5

from __future__ import division
def jia(x,y):
 return x+y
def jian(x,y):
 return x-y
def cheng(x,y):
 return x*y
def chu(x,y):
 return x/y
operator={"+":jia,"-":jian,"*":cheng,"/":chu}
def f(x,o,y):
 p=operator.get(o)(x,y)
 print(p)
f(15,'/',5)

总结

以上就是本文关于Python分支结构(switch)操作简介的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

Python3+PyInstall+Sciter解决报错缺少dll、html等文件问题

Python3+PyInstall+Sciter解决报错缺少dll、html等文件问题

1 调试过程 用Python3.6+Sciter+PyCharm写了一个py测试脚本helloworld.py,该脚本中只含有一条语句“import sciter”。在PyCharm中运...

python3使用GUI统计代码量

本文实例为大家分享了python3使用GUI统计代码量的具体代码,供大家参考,具体内容如下 # coding=utf-8 ''' 选择一个路径 遍历路径下的每一个文件,统计代码量 字...

学习python中matplotlib绘图设置坐标轴刻度、文本

学习python中matplotlib绘图设置坐标轴刻度、文本

总结matplotlib绘图如何设置坐标轴刻度大小和刻度。 上代码: from pylab import * from matplotlib.ticker import Multi...

对python中assert、isinstance的用法详解

1. assert 函数说明: Assert statements are a convenient way to insert debugging assertions into a...

Python PyInstaller库基本使用方法分析

Python PyInstaller库基本使用方法分析

本文实例讲述了Python PyInstaller库基本使用方法。分享给大家供大家参考,具体如下: 概述 将.py源码转换成无需源代码的可执行文件 .py文件 -> PyIns...