About bloggers : Former Internet manufacturer tencent staff , Network security giant Venustech staff , Alibaba cloud development community expert blogger , WeChat official account java Quality creators of basic notes ,csdn High quality creative bloggers , Entrepreneur , Knowledge sharers , Welcome to your attention , give the thumbs-up , Collection .
In the actual development process , You will often encounter many identical or very similar operations , At this time , Code that implements similar operations can be encapsulated as functions , Then call the function where you need it . This can not only realize code reuse , It can also make the code more organized , Increase code reliability . Now let's introduce python Nested function calls of .
Python It also allows you to call another function in one function , This is the nested call of a function .
Python Support recursive calling of functions , Recursion is a function that directly or indirectly calls itself .
example : Calculation 1!+2!+3!+…+10! And output , Use nested calls of functions to implement .
def fac(k): # Definition fac function , Calculate the factorial
i = 2
t = 1
while i <= k:
t *= i
i = i + 1
return t # Returns the factorial result
def sum(n): # Definition sum function , Add up
s = 0
i = 1
while i <= n:
s = s + fac(i) # call fac function
i += 1
return s # Returns the cumulative result
print('1!+2!+3!…10!=',sum(10)) # call sum function
give the result as follows .
Call directly recursively , Indirect recursive call , Both recursive calls are endless calls to themselves . therefore , To prevent infinite recursion , All recursive functions need to set the termination condition .
example : Calculation n The factorial .
def f(n): # Define recursive functions
if n==1: # When n be equal to 1 When to return to 1
return 1
else: # When n Not for 1 Is to return f(n-1)*n
return f(n-1)*n
n = int(input(' Please enter a positive integer :')) # Enter an integer
print(n,' The factorial result of is :',f(n)) # Call function f And output the result
give the result as follows .
1、 Liao Xuefeng's official website
2、python Official website
3、Python Programming case tutorial
The above is about Python Knowledge about nested function calls based on , You can refer to it , If you think it's good , Welcome to thumb up 、 Collection 、 Looking at , Welcome to wechat search java Basic notes , Relevant knowledge will be continuously updated later , Make progress together .