Catalog
1. Defined function :
1.1 Passing information to a function
1.2 Arguments and formal arguments
2. Transfer argument :
2.1 Location parameter
2.1 Keyword arguments
2.2 The default value is :
2.3 Equivalent function call
2.4 Avoid argument errors
3. Return value
3.1 Returns a simple value
3.2 Make arguments optional
3.3 Return dictionary
4. Delivery list
4.1 Disable function modification list
5. Pass any number of arguments :
5.1 Use a combination of positional arguments and any number of arguments
6. Store functions in modules :
6.1 Import the entire module import
6.2 Import specific functions
6.3 Use as Give the function an alias
6.4 Use as Assign an alias to a module
6.5 Import all functions in the module , Use *
Use keywords def To define a function
def introduction():
print("Hello world!")
greet_user()
def introduction(username):
print("Hello world!")
introduction('Xixi')
With 1.1 As an example , In function introduction() The definition of :
Variable username It's a Shape parameter --- A piece of information required by a function to complete its work .
In the code introduction('Xixi') in , value 'Xixi' It's a Actual parameters , An argument is the information passed to the function when it is called .
def person(username,old):
print("I am" + username + ".")
print("I am" + old + "years old.")
person('Xixi','3')
The output result is :
I am Xixi.
I am 2 years old.
The order of positional arguments is important ! If you need to call this function multiple times , Just call... Again person() that will do .
The order of keyword arguments is not required , because Python Know which formal parameter the values should be stored in . The following two function calls are equivalent :
def person(username,old):
person(username='aa', old='two')
person(old='one',username='aa')
Be careful : When using keyword arguments , Be sure to specify the parameter name in the function definition exactly .
When an argument is provided to a formal parameter in the calling function ,Python The specified argument value will be used ; otherwise , The default value of the formal parameter will be used . therefore , After a parameter is assigned a default value , You can omit the corresponding arguments in the function call . Use default values to simplify function calls , The typical usage of functions can also be clearly pointed out .
# Set formal parameter old The default value of is set to '3'
def person(username,old='3'):
Be careful : When using default values , In the formal parameter list, the formal parameter without default value must be listed first , Then list the arguments with default values . This makes Python Still able to correctly interpret location arguments .
def pet(petname, anmal_type = 'cat'):
print("hhhhh")
# The following function calls are equivalent
pet('xxx')
pet(petname = 'xxx')
pet('aaa','dog')
pet(petname = 'aaa', anmal_type = 'dog')
pet(anmal_type = 'dog', petname = 'aaa')
If argument mismatch occurs , You're going to report a mistake . appear traceback
In the function , You can use return sentence Return the value to the code line of the calling function . Functions do not always display output directly , contrary , It can process some data , And return one or a set of values . The value returned by a function is called the return value .
def get_name(first_name, last_name):
""" Return clean name """
full_name = first_name + ' ' + last_name
return full_name.title()
singer = get_name('jimi', 'hendrix')
print(singer)
def get_name(first_name, last_name, middle_name=''):
if middle_name:
full_name = first_name + ' ' + middle_name + ' ' + last_name
else:
full_name = first_name + ' ' + last_name
return full_name.title()
singer = get_name('kiki', 'hix')
print(singer)
musician = get_name('jon', 'lua', 'joe')
print(singer)
def build_pet(name, age):
""" Return a dictionary , It contains information about a pet """
pet = {'first': name, 'last': age}
pet person
cat = build_person('kiki', '12')
print(cat)
def build_pet(name):
for name in names:
greeting = "Hello, " + name.title() + "!"
print(greeting)
petnames = ['cat', 'dog', 'tiger']
build_pet(petnames)
build_pet(list_name[:])
You can add a before the formal parameter in the first line *, for example :def build_pet(*age):
If you want a function to accept different types of arguments , Formal parameters of any number of arguments must be placed last in the function definition .Python First match location arguments and keyword arguments , Then collect the remaining arguments into the last parameter .
def build_pet(name ,*age):
Create a a.py file , Creating a b.py file , You can import the first file into the second file
from xxx import xxx
By separating function names with commas , You can import any number of functions from the module as needed :
from xxx import function1,function2,function3
from B import A as mp
import A as mp
from A import *
The learning content of this article refers to 《Python Programming : From introduction to practice 》