Introduction to Python branch structure (switch) operation

  • 2020-07-21 08:42:50
  • OfStack

There is no switch statement in Python, this paper mainly studies the realization of the function of switch statement through the dictionary, as follows.

The switch statement is used to write programs with multi-branch structures, similar to the if... . elif... else statements.

The switch statement expresses a more branched structure than if... elif... The else statement is clearer and the code is more readable

However, python does not provide the switch statement.

python can realize the function of switch statement through the dictionary. The realization method is divided into two steps:

First, define a dictionary

Second, call get() of the dictionary to get the corresponding expression.

Calculator:


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)

Use the dictionary to implement the switch operation


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["+"] Is equivalent to jia
print (jia(3,2)) #operator["+"](3,2) Is equivalent to jia(3,2)

Operation results:
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)

conclusion

That's the end of this article's introduction to the Python branch structure (switch) operation, and I hope you found it helpful. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: