The main function of the function : Packaging code . benefits :1. Maximize code duplication , Reduce redundant code .2. Code with different functions can be encapsulated 、 decompose , So as to reduce the complexity of the structure , Improve the readability of the code .
Create and invoke Code : use def To define a function , Write the function name directly when calling .
>>> def myfunc():
for i in range(3):
print('i love fishc')
>>> myfunc
<function myfunc at 0x0000016F2DB70A60> // Error reason not written (), You cannot write only the function name when calling a function
>>> myfunc()
i love fishc
i love fishc
i love fishc
The parameters of the function : Realize the personalized design of functions through parameters , Parameters can be multiple , There are formal parameters and actual parameters , Formal parameters : The name of the parameter written when the function is defined , The actual parameter : Parameters passed in when calling a function .
>>> def myfunc(name):
for i in range(3):
print(f'i love {name}')
>>> myfunc(python)
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
myfunc(python)
NameError: name 'python' is not defined //python No quotes , The expression in quotation marks is a character .
Correct code :
>>> def myfunc(name):
for i in range(3):
print(f"i love {name}.") // Use f character string take name Characters of
>>> myfunc("python") // Be sure to quote
i love python.
i love python.
i love python.
In the case of multiple parameters :
>>> def myfunc(name, times):
for i in range(times):
print(f'i love {name}.')
>>> myfunc("python", 5)
i love python.
i love python.
i love python.
i love python.
i love python.
Function return value : Use return Statement can make the custom function implementation return . Function execution return Statement will immediately return directly to , It doesn't matter if there are other statements .
>>> def div(x, y)
SyntaxError: invalid syntax // Be sure to use a colon , At the time of definition
>>> def div(x, y):
z = x / y
return z
>>> div(2, 1)
2.0
>>> def div(x, y):
return x / y
>>> div(2, 1)
2.0
>>> def div(x, y):
if y == 0:
return " The divisor cannot be zero 0"
else:
return x / y
>>> div(6, 0)
' The divisor cannot be zero 0'
>>> div(6, 3)
2.0
If we fail a function return Statement to display the returned contents , Then it will execute everything in the function body , Return to one None.
>>> def myfunc():
pass
>>> print(myfunc())
None