We have seen some Python built-in functions, such as Len and rang. Now let's take a look at the custom function. The function is defined by the def keyword, followed by the function name and parentheses. The brackets can contain parameters. This row ends with a colon, followed by the statement block, that is, the function body.
1. Simple sayhello Function
Def sayhello (): Print ("Hello world! ") # Call the function sayhello ()
2. Functions with Parameters
Def printmax (A, B): If A> B: Print (a, "is maximum. ") else: Print (B," is maximum. ") printmax (3, 4)
3. Local Variables
Def func (x): Print ("X is", x) x = 2 print ("changed local X to", x) x = 50 func (X) print ("X is still", X)
The running result is:
X is 50
Changed local X to 2
X is still 50
4. default parameter values
Def say (message, Times = 1): Print (Message * times) Say ("ha") Say ("ha", 2)
The running result is:
Ha
Haha
5. Key Parameters
Def func (a, B = 5, c = 10): Print ("A is", a, "and B is", B, "and C is", c) func (3, 7) func (25, c = 24) func (C = 50, A = 100)
The running result is:
A is 3 and B is 7 and C is 10
A is 25 and B is 5 and C is 24
A is 100 and B is 5 and C is 50
6. Return Statement
Def maximum (x, y): If x> Y: Return x else: Return yprint (maximum (2, 3 ))
7. docstrings
Python has a wonderful feature: docstrings. Its main function is to help youProgramThe document is easier to understand.
Def printmax (x, y): ''' prints the maximum of two numbers. the two values must be integers. '''x = int (x) y = int (y) If x> Y: Print (x, "is maximum. ") else: Print (Y," is maximum. ") printmax (3, 5) print (printmax. _ Doc _) Help (printmax)
The running result is:
5 is maximum.
Prints the maximum of two numbers.
The two values must be integers.
Help on function printmax in module _ main __:
Printmax (x, y)
Prints the maximum of two numbers.
The two values must be integers.