[Python] basic functions, python Functions
Use def function name (): to define a function. The function body is written in the form of an indention block. The returned result is return xx.
For example:
Def myAbs (x ):
If x> = 0:
Return x
Else:
Return-x
Variable parameters
Add a * sign before the parameter. The parameter received in the function is of the tuple type. traverse it.
# Variable parameters
Def myCalc (* nums ):
Sum = 0
For num in nums:
Sum + = num
Return sum
Print (myCalc (1, 2, 3 ))
Iteration
List or tuple traversal through a for loop is called iteration.
Use for in to iterate the list, for key in list:, for example:
For item in myList:
Print (item)
Use for in to iterate dict, for k, v in d. items:, for example:
User = {"name": "taoshihan", "age": "100 "}
For k, v in user. items ():
Print (k + "=>" + v)
Slice
Take some elements of a list or tuple and use the slice operator list [a: B]. The elements of the list start from a to B (excluding B)
Example: myList = [1, 2, 3]
Print (myList [0: 2]) Output [1, 2]
Function Recursion
Returns the factorial (n!) of n !)
Def myFact (n ):
If n = 1:
Return 1
Return myFact (n-1) * n
Print (myFact (30 ))
Tail recursion optimization is used to solve the stack overflow problem. The return statement cannot contain expressions, but the Python language does not introduce tail recursion. Therefore, it cannot be used.
Solve the following problems:
Def myMove (n, source, bridge, destination ):
If n = 1:
Print ("from" + source + "mobile" + "to" + destination)
Else:
MyMove (n-1, source, destination, bridge)
Print ("from" + source + "mobile" + "to" + destination)
MyMove (n-1, bridge, source, destination)
MyMove (5, "a", "B", "c ")
Function programming features: allows the function itself to be passed into another function as a parameter, and allows the return of a function