# Custom function
def func(a, b):
print(a ** b)
# Normal call
func(2,3)
------------------------------------------------------------------
Running results :
8
2 ** 3 =2*2*2=8
If the number of arguments and formal parameters are inconsistent, a syntax error will be reported , Such as calling func Function only passes in the result of an argument
# Custom function
def func(a, b):
print(a ** b)
# The number of arguments and parameters must be the same
func(2)
----------------------------------------------------------------------
Running results :
TypeError: func() missing 1 required positional argument: 'b'
Empathy , Multiple incoming parameters will also be reported TypeError
# Custom function
def func(a, b):
print(a ** b)
# Argument and parameter positions must be the same
func(2, 3)
func(3, 2)
-----------------------------------------------------------------------
Running results :
8
9
2 ** 3 = 2*2*2 = 8
3 ** 2 = 3*3 = 9
The results show that , The positions of formal and actual parameters must be consistent ,func(2,3) and func(3,2) It's different .
# Custom function
def func(a, b):
print(a ** b)
# Normal call
func(a=2, b=3)
func(b=3,a=2)
----------------------------------------------------------
Running results :
8
8
We can easily draw a conclusion from the above example , It is no longer necessary to be exactly the same as the position of the parameter , Just write the parameter name correctly .
# Custom function
def func(a, b):
print(a ** b)
func(2, b=3)
-------------------------------------------------------------------------
Running results :
8
# Custom function
def func(a, b):
print(a ** b)
func(a=2, 3)
--------------------------------------------------------------------------------
Running results :
SyntaxError: positional argument follows keyword argument
We can easily draw a conclusion from the above example , Keyword parameters can be mixed with positional parameters , But the keyword parameter must be after the positional parameter , Otherwise you will report a syntax error SyntaxError
# Custom function , Parameters with default values must follow all parameters without default values
def func(a, b=3):
print(a ** b)
# Default parameters
func(2)
func(2,1)
-----------------------------------------------------------------------
Running results :
8
2
The results show that , Corresponding to the default parameter , When calling a function, if no arguments are passed in , The default parameter is taken . If you pass in an argument , Then take the actual parameter .