python中分支结构包括哪些_Python分支结构(switch)操作简介
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)操作簡介的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
本文標題: Python分支結構(switch)操作簡介
本文地址: http://www.cppcns.com/jiaoben/python/218014.html
總結
以上是生活随笔為你收集整理的python中分支结构包括哪些_Python分支结构(switch)操作简介的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jar 工程我怎么在网页上url访问某一
- 下一篇: websocket python爬虫_p