Basic concepts of functions
def greet_user( username ): print( "Hello, " + username.title() + "!" ) greet_user( 'jesse' )
Output is:
Hello, Jesse!
This is a relatively simple function. The first line is called function definition, which indicates the function name to Python, and also contains the information required by the function to complete its task in parentheses. These parameters are called formal parameters. All contractions immediately following the definition statement form the body of the function.
The fourth line is the function call, which lets Python execute the code of the function. The parameter in parentheses is called an actual parameter. This value is stored in the formal parameter in the calling function to provide necessary information for the function to complete the corresponding work.
Several ways of passing arguments
1. Positional arguments
According to the order of formal parameters, the corresponding arguments are given in turn.
def describe_pet( animal_type, pet_name ): print( "I have a " + animal_type + "." ) print( "My " + animal_type + "'s name is " + pet_name.title() + "." ) describe_pet( 'hamster' , 'harry' )
Output is:
I have a hamster. My hamster's name is Harry.
2. Keyword arguments
Keyword arguments are name value pairs that are passed to functions. Names and values are directly associated in the arguments, so there is no confusion when passing arguments to functions.
When keyword arguments are used, the order of different arguments can be changed at will, and the passed results remain the same (as long as the name value correspondence is not changed).
def describe_pet( animal_type, pet_name ): print( "I have a " + animal_type + "." ) print( "My " + animal_type + "'s name is " + pet_name.title() + "." ) describe_pet( animal_type = 'hamster' , pet_name = 'harry' ) '''The following function calls are equivalent to the above''' describe_pet( pet_name = 'harry' , animal_type = 'hamster' )
3. Given default value
When defining a function, you can specify a default value for each parameter. When no arguments corresponding to these formal parameters are given when calling a function, they will run their default values as arguments by default; When the corresponding arguments are given, they are used to run.
def describe_pet( pet_name , animal_type = 'dog' ): print( "I have a " + animal_type + "." ) print( "My " + animal_type + "'s name is " + pet_name.title() + "." ) describe_pet( pet_name = 'willie' )
\n\n note: formal parameters with a given default value should be listed in the back, and those without a given default value should be listed in the front, otherwise the compiler will report an error.
Complex parameter transfer problem
1. Pass any number of arguments
Used when you do not know in advance how many arguments a function requires
def make_pizza( *toppings ):
'''Print all ingredients'''
print( "\nMaking a pizza with the following toppings:" )
for topping in toppings:
print( "- " + topping )
make_pizza( 'pepperoni' )
make_pizza( 'mushrooms' , 'green peppers' , 'extra cheese' )
Output is:
Making a pizza with the following toppings:
- pepperoniMaking a pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
The formal parameter name *asterisk in toppings * allows Python to create an empty tuple named toppings and load all received values into this tuple.
2. Use position arguments with any number of arguments
If you want a function to accept different types of arguments, you must put the formal parameters that accept any number of arguments last in the function definition. Python first matches the position argument with the keyword argument, and then collects the remaining arguments into the last formal parameter.
def make_pizza( size, *toppings ): '''Overview of pizza to be made''' print( "\nMaking a " + str( size ) + "-inch pizza with the following toppings:" ) for topping in toppings: print( "- " + topping ) make_pizza( 16, 'pepperoni' ) make_pizza( 12, 'mushrooms' , 'green peppers' , 'extra cheese' )
Output is:
Making a 16-inch pizza with the following toppings: - pepperoni Making a 12-inch pizza with the following toppings: - mushrooms - green peppers - extra cheese
3. Use any number of keyword arguments
def build_profile( first, last, **user_info ): '''Create a dictionary that contains information about users''' profile = { } profile[ 'first_name' ] = first profile[ 'last_name' ] = last for key, value in user_info.items(): profile[ key ] = value return profile user_profile = build_profile( 'albert' , 'einstein' , location = 'prinston' , field = 'physics' ) print( user_profile )
Output is:
{'first_name': 'albert', 'last_name': 'einstein', 'location': 'prinston', 'field': 'physics'}
Where the formal parameter name * *user_ The two asterisks in info let Python create a user_info, and encapsulate the received name value pairs in this dictionary. In this function, you can access the user as you access other dictionaries_ Name value pairs in info.
Return value
The value returned by the function to the main program is called the return value. The return statement can be used to return the value to the code line of the calling function, thus simplifying the main program.
1. Return simple value
def get_formatted_name( first_name, last_name ) full_name = first_name + " " + last_name return full_name.title() musician = get_formatted_name( 'jimi' , 'hendrix' ) print( musician )
Output is:
Jimi Hendrix
2. Make arguments optional
When not all cases need to return a variable, you can make this argument optional by specifying a default value - empty string for their corresponding formal parameters.
def get_formatted_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() musician = get_formatted_name( 'jimi' , 'hendrix' ) print( musician ) musician = get_formatted_name( 'john' , 'hooker' , 'lee' ) print( musician )
Output is:
Jimi Hendrix
John Lee Hooker
3. Return to dictionary
def build_person( first_name, last_name, age = '' ): person = { 'first' : first_name, 'last' : last_name } if age: person[ 'age' ] = age return person musician = build_person( 'jimi' , 'hendrix' , age = 27 ) print( musician )
Output is:
{'first': 'jimi', 'last': 'hendrix', 'age': 27}
Pass list to function
1. Simple list delivery
def greet_users( names ): for name in names: message = "Hello " + name.title() + "!" print( message ) usernames = [ 'hannah' , 'ty' , 'margot' ] greet_users( usernames )
Output is:
Hello Hannah!
Hello Ty!
Hello Margot!
2. Modify list in function
Rewrite the following procedure:
'''Create a list of designs to print''' unprinted_designs = [ 'iphone case' , 'robot pendant' , 'dodecahedron' ] completed_models = [ ] '''Print each design until there are no unprinted designs''' '''After printing each design, move it to the list unprinted_models in''' while unprinted_designs: current_design = unprinted_designs.pop() print( "Printing model: " + current_design ) completed_models.append( current_design ) '''Show all printed models''' print( "\nThe following models have been printed:" ) for completed_model in completed_models: print( completed_model )
The program output is:
Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case
The following models have been printed:
dodecahedron
robot pendant
iphone case
Two functions are introduced to achieve the same function:
def print_models( unprinted_designs, completed_models ): '''Print each design and move them to the list completed_models in''' while unprinted_designs: current_design = unprinted_designs.pop() print( "Printing model: " + current_design ) completed_models.append( current_design ) def show_completed_models( completed_models ): '''Show all printed models''' print( "\nThe following models have been printed:" ) for completed_model in completed_models: print( completed_model ) '''main program''' unprinted_designs = [ 'iphone case' , 'robot pendant' , 'dodecahedron' ] completed_models = [ ] print_models( unprinted_designs, completed_models ) show_completed_models( completed_models )
3. Keep original list
By passing a copy of the list created by the slice representation ([:]) to the function instead of the original, the relevant changes in the function only affect the copy of the list instead of the original, thus preserving the original list.
'''The transfer format is as follows''' function_name( list_name[ : ] ) '''for example''' print_models( unprinted_designs[ : ], completed_models )
module
Store the functions in a separate file called a module, and then import the module into the main program. Use the import statement to use the code in the module in the currently running program file.
Using modules allows you to focus on the high-level logic of the program, and allows you to use the functions of the program in other programs.
1. Create module
The module has an extension of py, which contains the function code you want to import into other programs, such as:
def make_pizza( size, *toppings ): '''Overview of pizza to be made''' print( "\nMaking a " + str( size ) + "-inch pizza with the following toppings:" ) for topping in toppings: print( "- " + topping ) '''Save the above code in a file named pizza.py In the file'''
2. Several ways of importing modules and calling functions in modules
(1) Import entire module
Syntax: import module_name module_name.function_name()
For example:
import pizza
pizza.make_pizza( 16, 'pepperoni' )
When Python reads this file, the code line import pizza causes Python to open the file pizza Py, and copy all the functions into this program. So that in the current file, you can use pizza Py.
When the module to be imported conflicts with the existing name in the program, is too long, or cannot use the original name for other reasons, you can use as to specify an alias for it.
Syntax: import module_name as mn mn.function_name() For example: import pizza as p p.make_pizza( 16, 'pepperoni' )
(2) Import specific functions
Syntax: from module_name import function_name function_name() For example: from pizza import make_pizza make_pizza( 16, 'pepperoni' )
Like modules, functions can also be aliased with as.
Syntax: from module_name import function_name as fn fn() For example: from pizza import make_pizza as mp mp( 16, 'pepperoni' )
(3) Import all functions in the module
Using the asterisk (*) operator allows Python to import all functions in the module
Syntax: from module_name import * function_name() For example: from pizza import * make pizza( 16, 'pepperoni' )
However, it is best not to use this method when using large modules that are not written by yourself. If the function name in the module is the same as that in the current program, unexpected results may occur. Therefore, unless there are special circumstances, it is best to use the first two import methods.
Reference book: Python Programming: from introduction to practice
2020-07-14