python 中无switch(写了几个函数代替switch)
字典的常用用途之一代替switch
在C/C++/Java语言中,有个很方便的函数switch,比如:
代码如下:
public class test { public static void main(String[] args) { String s = "C"; switch (s){ case "A": System.out.println("A"); break; case "B": System.out.println("B"); break; case "C": System.out.println("C"); break; default: System.out.println("D"); } } }
在Python中要实现同样的功能,
方法一,就是用if, else语句来实现,比如:
from __future__ import division
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
return x / y
def operator(x, y, sep=‘+‘):
if sep == ‘+‘: print add(x, y)
elif sep == ‘-‘: print sub(x, y)
elif sep == ‘*‘: print mul(x, y)
elif sep == ‘/‘: print div(x, y)
else: print ‘Something Wrong‘
print __name__
if __name__ == ‘__main__‘:
x = int(raw_input("Enter the 1st number: "))
y = int(raw_input("Enter the 2nd number: "))
s = raw_input("Enter operation here(+ - * /): ")
operator(x, y, s)
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
return x / y
def operator(x, y, sep=‘+‘):
if sep == ‘+‘: print add(x, y)
elif sep == ‘-‘: print sub(x, y)
elif sep == ‘*‘: print mul(x, y)
elif sep == ‘/‘: print div(x, y)
else: print ‘Something Wrong‘
print __name__
if __name__ == ‘__main__‘:
x = int(raw_input("Enter the 1st number: "))
y = int(raw_input("Enter the 2nd number: "))
s = raw_input("Enter operation here(+ - * /): ")
operator(x, y, s)
方法二,用字典来巧妙实现同样的switch的功能,比如:
代码如下:
#coding=gbk from __future__ import division x = int(raw_input("Enter the 1st number: ")) y = int(raw_input("Enter the 2nd number: ")) def operator(o): dict_oper = { ‘+‘: lambda x, y: x + y, ‘-‘: lambda x, y: x - y, ‘*‘: lambda x, y: x * y, ‘/‘: lambda x, y: x / y} return dict_oper.get(o)(x, y) if __name__ == ‘__main__‘: o = raw_input("Enter operation here(+ - * /): ") print operator(o)
相关推荐
夜斗不是神 2020-11-17
huavhuahua 2020-11-20
Yasin 2020-11-16
xiaoseyihe 2020-11-16
千锋 2020-11-15
diyanpython 2020-11-12
chunjiekid 2020-11-10
wordmhg 2020-11-06
世事一场大梦 2020-11-17
xiaoseyihe 2020-11-16
Morelia 2020-11-03
CloudXli 2020-11-03
文山羊 2020-10-31
comtop0 2020-10-31
pythonxuexi 2020-10-30
三石 2020-10-29
chaochao 2020-10-27
PythonMaker 2020-10-27