python不提供switch語句,但是python可以通過字典實現switch語句的功能
實現方法分兩步:
首先:定義一個地點
其次:調用字典的get()獲取相應的表達式
原始方法:
from __future__ import division #內置函數,解決整型除以整型得不到小數
jia = lambda x, y:x +y
jian= lambda x, y:x -y
chen= lambda x, y:x *y
chu= lambda x, y:x /ydefcz(x, o, y):if o == '+':print(jia(x, y))elif o == '-':print(jian(x, y))elif o == '*':print(chen(x, y))elif o == '/':print(chu(x, y))else:print('請輸入+-*/')
x= int(input('輸入第一個數字:'))
y= int(input('輸入第二個數字:'))
o= input('輸入運算符:')
cz(x, o, y)
用字典方法:
from __future__ import division #內置函數,解決整型除以整型得不到小數
jia = lambda x, y:x +y
jian= lambda x, y:x -y
chen= lambda x, y:x *y
chu= lambda x, y:x /y
x= int(input('輸入第一個數字:'))
y= int(input('輸入第二個數字:'))
o= input('輸入運算符:')
cz= {'+':jia, '-':jian, '*':chen, '/':chu}print(cz[o](x, y))
最優get()獲取
from __future__ importdivision
x= int(input('1:'))
y= int(input('2:'))
operator= input('+ - * /:')
result= {'+':x+y, '-':x-y, '*':x*y, '/':x/y}print(result.get(operator))