function
Definition of the function:
def function name ():
function body
Return returns a value of 1, which returns a value of 2.
Call to function:
Name of function ()
? Implement print return value : Print function name ()
? Summary :
- function is not executed when the function is defined ;
- function is executed only when the function is called ;
function with parameters
Required Parameters
# Formal Parameters
# Arguments , x=1, y=2;
Add(1 2)
3
Default parameters
def mypow (x,y=2):
Print X**y
Variable parameters
# Formal Parameters
# args can be changed to other variable names ;
def add (*args):
# args is essentially a tuple ;
# Print Args
sum = 0
For i in args:
sum + = i
Print sum
Keyword parameters
# Kwargs can be changed to another variable name ;
def inuser (name, age, **kwargs):
# Kwargs is essentially a dictionary ;
Print name, name, Kwargs
Inuser ("user1" city= "Xi ' an" birth= "20180101")
default Parameters , > variable Parameters , > keyword Parameters
return value
If there is no return in the function , the default return is none;
Return multiple values
Scope of the function
The global keyword must first be declared and then assigned ;
# Global Variables
Advanced Features
Slice
Iteration
? Whether you can for the object that iterates through ;
Isinstance Judge whether the iteration can be iterative ;
List-Generated
? formulas for generating lists
? Demand : Generate a list , return 1-100 The square of the even number ;([4, .....]
# Method 1:
# Method 2:
[I**2 for I in range (2 20 2)]
[4, 16, 36, 64, 100, 144, 196, 256, 324]
Variant list of generated formula
# for loop nested if statement
# for loop nested for Loop, two string full array
python--function