[ TOC]
WeiyiGeek. The correspondence between basic data types in Python and C
Description: It took a long time to learn python language, and it took a long time to find that python does not have switch-case statement. Checking the official document says that it can be replaced by if-elseif-elseif. At the same time, other solutions are simpler to use a dictionary to achieve the same function.
Writing the value corresponding to each key of a dictionary is a method such as:
switch = {“valueA”:lambda x,y:functionA(x,y),”valueB”:functionB,”valueC”:functionC}
Sample demonstration:
#! /usr/bin/env python
# switch in python...case statement
# Function called
def add(x,y):print("case c: call add function in switch c dictionary form: %d + %d = %d"%(x,y,x+y))
def div(x,y):return"switch b dictionary calls the div function: %d + %d = %f"%(x,y,x/y)
# Lambda expression in dictionary form to achieve switch statement effect
switch={'a':lambda x:x**2,'b':lambda x,y:div(x,y),'c':lambda x,y:add(x,y)}
# Use try...except to catch exceptions
try:print("case a : ",switch["a"](2)) #4print("case b :",switch['b'](8,2)) #4.0switch["c"](2,5) #Call the function according to the dictionary key value#7
except KeyError as e:print("Caught exception!")
# Results of the
case a :4case b: switch b dictionary calls the div function:8+2=4.000000case c: call add function in switch c dictionary form:2+5=7
Question: How to understand the convention of function calling?
Answer: The function calling convention (calling convention) describes how to call certain types of functions in a correct way, including the order in which function parameters are allocated on the station, which parameters will be pushed onto the stack, and those parameters will pass through registers Incoming, and the way the function stack is recycled when the function returns;
The two most basic function calling conventions:
The same/difference between the two:
Three different dynamic library linking methods of ctype module:
Recommended Posts