Use the DEF Function name (): To define a function that is written as a indented block of the function body, returning the result as a return XX
For example:
def myabs (x):
If x >= 0:
return x
Else
Return–x
Variable parameters
Precede the parameter with an * number, the parameter received in the function is a tuple type, traversing
#可变参数
def mycalc (*nums):
Sum=0
For num in nums:
Sum+=num
return sum
Print (Mycalc ())
Iteration
Traversing a list or tuple through a for loop, which is called an iteration
Use for in to iterate over the List,for key in list: such as:
For item in MyList:
Print (item)
Use for in to iterate Dict,for k,v in D.items: such as:
user={"name": "Taoshihan", "Age": "100"}
For k,v in User.items ():
Print (k + "=" +v)
Slice
Take a list or tuple element, use the slice operator list[a:b], take the list of elements from A to B end (does not contain B)
Example: mylist=[1,2,3]
Print (Mylist[0:2]) output [1, 2]
function recursion
To find the factorial of n (n!)
def myfact (n):
If n==1:
Return 1
Return Myfact (n-1) *n
Print (Myfact (30))
Using tail recursion optimization to solve the stack overflow problem, the return statement cannot contain an expression, but the Python language does not introduce a tail recursion and therefore cannot be used
Solving the question of the Nottingham Tower:
def mymove (n,source,bridge,destination):
If n==1:
Print ("Move +" to "+destination" from "+source+")
Else
Mymove (N-1,source,destination, Bridge)
Print ("Move +" to "+destination" from "+source+")
Mymove (n-1,bridge,source,destination)
Mymove (5, "A", "B", "C")
Features of functional programming: Allows the function itself to be passed as a parameter to another function, and also allows the return of a function
[Python] Function basic