A Python function is a block of statements with a function name.
- Does a certain function
- Can accept data (parameters)
- A function is called by its name
- Functions can return data
Not to be confused with the mathematical definition of a function:
y = f(x), y is a function of x and x is an independent variable.
Related course: Complete Python Programming Course & Exercises
The role of the function is:
- Structured programming is the most basic encapsulation of code, generally organizing a piece of code by function
- The purpose of packaging is to reuse and reduce redundant code
- The code is simple and easy to read and understand
Classification of functions:
- Built-in functions such as
- library functions, such as
- Custom functions, defined using the def keyword
How to Define a Function in Python?
You can define a Python function like this:
def function name (list of arguments). Function body (code block) [return function value]
Some facts about functions:
- Function names are identifiers, same naming requirements
- Statement blocks must be indented, 4 spaces
- Python functions that do not have a return statement will return a None value
The list of parameters in a definition is called a formal parameter
def add(x,y): return x+y
How to Call a Function in Python?
The definition of a function, which declares only one function, is not executed and needs to be called in order to be executed. Call:
The parameters written at the time of call are the actual parameters, abbreviated as real parameters.
Parameters of the function
The function is defined to agree on the formal parameters and to provide enough actual parameters when called, in general, the number of formal and actual Method of transmission
The location parameter is required to be passed in before the keyword is passed in, and the location parameter corresponds to the location.
Can a Function have default parameter value?
The default value, also known as the default value, can be added to a function at the time of function definition.
The default value of a parameter can be set to the default value for a parameter without a given real parameter when not enough real participants are
When there are many parameters, you don't need to enter all the parameters every time, simplifying parameter calls
def add(x=4,y=5): return x+y add() add(10) add(10,y=6) add(11,10)
Can def add(x, y=5) or def add(x=4, y) be defined this way?
def add(x=4, y) SyntaxError: non-default argument follows default argument
The #position parameter must be passed in before the keyword parameter
Python Function Variable Arguments
The use of * in front of the parameter indicates that the parameter is a variable position parameter and can accept more than one real parameter. It encapsulates the collected real participants into tuple groups.
Variable position parameters cannot be passed with keywords.
def fn(x,*args): print(x) print(args) fn(3,args=4) #error
What is Function scope?
The visible range of an identifier (variable).
Each function opens up a scope, and the variables within the function cannot be outside the scope of the function. Classification of scope:
- Visible throughout the program's operating environment.
- Variables in a global scope are called global variables
- visible within functions, classes, etc.
- A variable in a local scope is called a local variable and cannot be used more than the local scope in which it is located
1 In general, global scope variables are visible in all the program (and functions) 2 local variables cannot be seen or used outside the function.
Scopes of default values
def foo(x=1): x += 1 print(x) foo() foo()
Then try this:
def bar(x=): #reference type, address of x-reference  x.append print(x) bar() bar()
Can we have multiple return statements inside a Function?
A function can have multiple return statements, but only one is executed. The example below has multiple returns:
>>> def zero_or_one(x): ... if x == 0: ... return "zero" ... else: ... return "one" ... >>> zero_or_one(0) 'zero' >>> zero_or_one(1) 'one' >>>
Can you destroy functions?
Destruction of functions:
- Defining a function is generating a function object to which the function name points.
- You can use the del statement to delete the function so that its reference count is minus 1
- The original definition can be overwritten with an identifier of the same name, essentially reducing its reference count by 1
- Python program ends with all objects destroyed
- A function is also an object, no exception, whether to destroy or not, or whether to reduce the reference count to 0
Python Recursive Function
A recursive function is a special function:
- A recursive function will call itself
- It has a stopping condition.
An example of a recursive function is:
def fact(n): if n==1: return 1 else : return n * fact(n-1)
When called, it returns
n * fact(n-1). That means, it will keep calling itself until the stopping condtion
n==1 is True. An example run:
>>> def fact(n): ... if n == 1: ... return 1 ... else: ... return n * fact(n-1) ... >>> fact(5) 120 >>> fact(1) 1 >>> fact(2) 2 >>> fact(3) 6 >>>
Data Type of Python Function
The data type of a Python function is
function. Every function is an instance of the
function class. You can test this with the
>>> def bar(): ... pass ... >>> type(bar) <class 'function'>
Python Function vs Method
So what's the difference between a function and a method?
- A function is part of a Python script, and a collection of statements
- A method is part of a class
- Functions can be called any time, but methods need object creation
They have a different data type
Methods are harder to understand (classes, objects etc). Functions are just statements
Python Anonymous Function
An anonymous function is a function or subroutine that does not require a name (identifier) to be defined.
Python defines an anonymous function in lambda syntax, using only expressions and not declarations.
The lambda syntax is defined as follows.
lambda [arg1 [,arg2, ... argN]] : expression
The anonymous function has a restriction: there can only be one expression, no need to write return, the return value is the result of that expression.
There is an advantage to using anonymous functions because the function has no name and you don't have to worry about conflicting function names.
# Writable function description sum = lambda arg1, arg2: arg1 + arg2 # Call the sum function print("The sum of the values is : ", sum(10, 20)) print("The sum of the values is : ", sum(20, 20))
Above code, output.
The sum of the values is : 30 The summed value is : 40
It can be called directly at the time of definition, for example.
print((lambda x, y: x-y)(3, 4))
Above code, output.