程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Anonymous and recursive functions in Python

編輯:Python

Anonymous functions

Concept

Anonymous functions are a way of defining functions that do not need to be named , With lambda Keyword start

Example

lambda x:x*x
def getresult(x);
return x*x

In the above code block lambda Of x Corresponding to the following getresult In parentheses x,lambda Medium x*x Corresponding return hinder x*x

An anonymous function is called an anonymous function because it has no function name . Another example

# A function with only one parameter
square=lambda x:x*x
result=square(12)
print(result)
# Functions with multiple arguments
triangle=lambda x,y:0.5*x*y
result=triangle(23,4)
print(result)

Be careful

  1. When you want to pass in multiple parameters , The parameters should be separated by commas .
  2. Don't leave out the colon , The colon here is a way for anonymous functions to fix the format , After the colon is how to calculate the input value before the colon .
  3. The colon is followed by the return value of the function , Note that there is no need to use return Keyword before square and triangle It's a variable. , Assign an anonymous function to a variable , Then the function is called by this variable .
  4. When a function is called, it still needs to use parentheses to pass parameters .

limited

lambda The subject of is an expression , Not a block of code , It is not suitable for dealing with complex logical situations .

When we create a function that contains more complex logic , It is recommended to use def Create a function .

Recursive function

The internal calling function of the function itself , This self calling function is a recursive function

def sun(n)
if n<=0:
return 0
return n+sum(n-1)
print(sum(5))

The above recursive function is used to calculate the accumulation of numbers ( Calculation 5 Number accumulation within )

In recursive functions ,if Judgment is the termination condition , In the above example , When n<=0 when , Just go back to 0, Recursion ends

If there are no conditions , It's a dead circle .

 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved