8.1 Define Functions
A simple function
def greet_user(): '''Show simple greetings''' print('Hello!') greet_user() ''' Output: Hello! '''
8.1.1 Passing Information to Functions
def greet_user(username): # Show simple greetings print(f'Hello, {username.title()}.') greet_user('jesse') greet_user('jim') ''' Output: Hello, Jesse. Hello, Jim. '''
8.1.2 Formal and Actual Parameters
In the code above, the variable username is a parameter, and the values'jesse'and'jim' are arguments
8.2 Transfer parameters
Function definitions may include more than one parameter, and function calls may include more than one argument. The methods for passing arguments to a function are: positional arguments, keyword arguments
8.2.1 Positional arguments
When calling a function, associate arguments to parameters based on their position
def describe_pet(animal_type, pet_name): '''Show pet information''' print(f"\nI have a {animal_type}.") print(f"My {animal_type}'s name is {pet_name}.") describe_pet('mouse', 'Micky') describe_pet('dog', 'Harry') describe_pet('Harry', 'dog') ''' I have a mouse. My mouse's name is Micky. I have a dog. My dog's name is Harry. I have a Harry. My Harry's name is dog. '''
- Calling functions multiple times
- The order of positional arguments is important, as illustrated by the second and third calls
8.2.2 Key Arguments
Keyword arguments associate names with values directly in the argument, so that the order of arguments is not considered
def describe_pet(animal_type, pet_name): '''Show pet information''' print(f"\nI have a {animal_type}.") print(f"My {animal_type}'s name is {pet_name}.") describe_pet(animal_type = 'mouse',pet_name = 'Micky') describe_pet(pet_name = 'Micky', animal_type = 'mouse') ''' Output: I have a mouse. My mouse's name is Micky. I have a mouse. My mouse's name is Micky. Process ended with exit code of 0 '''
8.2.3 Default
When writing a function, you can specify a default value for the parameter. When calling a function, when you provide an argument for the parameter, the program will use the supplied argument, otherwise the default value for the parameter will be used
Note here that it is important to consider the parameter position (where the parameter-default value also takes up a parameter position)
def describe_pet(pet_name, animal_type = 'mouse'): '''Show pet information''' print(f"\nI have a {animal_type}.") print(f"My {animal_type}'s name is {pet_name}.") describe_pet('Micky') describe_pet(pet_name = 'Harry', animal_type = 'dog') ''' Output: I have a mouse. My mouse's name is Micky. I have a dog. My dog's name is Harry.
8.2.4 Equivalent function call
You can mix location, keyword, and default values
8.2.5 Avoid argument errors
slightly
8.3 Return Value
Functions can return one or a set of values using the return statement
8.3.1 Returns a simple value
def get_formatted_name(first_name, last_name): '''Return a neat name''' full_name = f"{first_name} {last_name}" return full_name.title() musician = get_formatted_name('jim', 'hendrix') print(musician) ''' Output: Jim Hendrix
8.3.2 Make arguments optional
Not everyone has a middle name. To make the middle name optional, move the middle name to the end of the parameter, using the default method
def get_formatted_name(first_name, last_name, middle_name = ''): '''Return a neat name''' if middle_name: full_name = f"{first_name} {middle_name} {last_name}" else: full_name = f"{first_name} {last_name}" return full_name.title() musician = get_formatted_name('jim', 'hendrix') print(musician) musician = get_formatted_name('john', 'hooker', 'lee') print(musician) ''' Output: Jim Hendrix John Lee Hooker '''
8.3.3 Return to Dictionary
def build_person(first_name, last_name): person = {'first': first_name, 'last': last_name} return person musician = build_person('jim', 'hendrix') print(musician) ''' Output: {'first': 'jim', 'last': 'hendrix'} '''
8.3.4 Combining functions with while loops
def get_formatted_name(first_name, last_name): '''Return a neat name''' full_name = f"{first_name} {last_name}" return full_name.title() while True: print("\nPlease tell me your name: ") print("(enter 'q' at any time to quit)") f_name = input("First name: ") if f_name == 'q': break l_name = input("Last name: ") if l_name == 'q': break formatted_name = get_formatted_name(f_name, l_name) print(f"\nHello, {formatted_name}!") ''' Output: Please tell me your name: (enter 'q' at any time to quit) First name: zhang Last name: xy Hello, Zhang Xy! Please tell me your name: (enter 'q' at any time to quit) First name: wang Last name: q '''
8.4 Delivery List
Pass a list to the function
def greet_users(names): for name in names: msg = f"Hello, {name.title()}." print(msg) usernames = ['hannah', 'ty', 'margot'] greet_users(usernames) ''' Output: Hello, Hannah. Hello, Ty. Hello, Margot. '''
8.4.1 Modifying lists in functions
Once a list is passed to a function, it can be modified, and the function is permanently modifying the list
Print elements from unprinted list, move elements from printed list to finished list
General procedure:
unprint_designs = ['phone case', 'robot pendant', 'dodecahedron'] completed_designs = [] while unprint_designs: current_design = unprint_designs.pop() print(f"Printing model: {current_design}") completed_designs.append(current_design) print("\nThe following models have been printed: ") for completed_design in completed_designs: print(completed_design) ''' Output: Printing model: dodecahedron Printing model: robot pendant Printing model: phone case The following models have been printed: dodecahedron robot pendant phone case '''
Optimize the code (each function tries to do only one thing, which is more effective, and the main function is more concise; the first function prints and moves list elements, and the second function displays printed information)
def print_modules(unprinted_designs, completed_designs): while unprinted_designs: current_design = unprint_designs.pop() print(f"Printing model: {current_design}") completed_designs.append(current_design) def show_completed_designs(completed_designs): print("\nThe following models have been printed: ") for completed_design in completed_designs: print(completed_design) unprint_designs = ['phone case', 'robot pendant', 'dodecahedron'] completed_designs = [] print_modules(unprint_designs, completed_designs) show_completed_designs(completed_designs) ''' Output: Printing model: dodecahedron Printing model: robot pendant Printing model: phone case The following models have been printed: dodecahedron robot pendant phone case '''
8.4.2 Disallow function modification list
Actually, instead of strictly prohibiting modification of the list, a backup is generated on the original list and operated on in the backup list so as not to affect the original list
function_name(list_name[:])
8.5 Pass any number of parameters
*The asterisk in toppings causes the program to create an empty tuple named toppings and load all values received into it
def make_pizza(*toppings): print("\nMaking a pizza with the following toppings: ") for topping in toppings: print(f"- {topping}") make_pizza('peperoni') make_pizza('mushrooms', 'green peppers', 'extra chesese') ''' Output: Making a pizza with the following toppings: - peperoni Making a pizza with the following toppings: - mushrooms - green peppers - extra chesese '''
8.5.1 Combines positional and any number of arguments
If a function accepts different types of arguments, it must put the last parameter that accepts any number of arguments so that the program matches the positional and keyword parameters before collecting the remaining arguments into the last parameter
def make_pizza(size, *toppings): print(f"\nMaking a {size}-inch pizza with the following toppings: ") for topping in toppings: print(f"- {topping}") make_pizza(16, 'peperoni') make_pizza(12, 'mushrooms', 'green peppers', 'extra chesese') ''' Output: Making a 16-inch pizza with the following toppings: - peperoni Making a 12-inch pizza with the following toppings: - mushrooms - green peppers - extra chesese '''
8.5.2 Use any number of keyword arguments
**user_info is used to collect any number of key-value pairs
def build_profile(first, last, **user_info): user_info['first_name'] = first user_info['last_name'] = last return user_info # Keyword arguments are stored as key-value pairs directly, and non-key arguments are stored as key-value pairs instead. user_proflie = build_profile('albert', 'einstein', location = 'princeton', field = 'physics') print(user_proflie) ''' Output: {'location': 'princeton', 'field': 'physics', 'first_name': 'albert', 'last_name': 'einstein'} '''
8.6 Store functions in modules
Use the import statement to make the current program use the code in the module, which can be understood as a stand-alone file with many useful functions
8.6.1 Import entire module
Using the pizza.py file as a module in making_ This module is called in pizza.py, and the syntax used to use the functions in the module is:
module_name.function_name()
pizza.py file
def make_pizza(size, *toppings): # pizza.py module, containing function make_pizza() print(f"\nMaking a {size}-inch pizza with the following toppings: ") for topping in toppings: print(f"- {topping}")
making_pizza.py file
import pizza pizza.make_pizza(16, 'pepperoni') pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') ''' Output: Making a 16-inch pizza with the following toppings: - pepperoni Making a 12-inch pizza with the following toppings: - mushrooms - green peppers - extra cheese '''
8.6.2 Import specific functions
Import the specific functions in the module with the following syntax:
from module_name import function_name
If multiple functions are imported, separate them with commas
from module_name import function0, function1, function2
In this case, you do not need to use the.Operator when calling a function
from pizza import make_pizza make_pizza(16, 'pepperoni') make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') ''' Output: Making a 16-inch pizza with the following toppings: - pepperoni Making a 12-inch pizza with the following toppings: - mushrooms - green peppers - extra cheese '''
8.6.3 Use as to alias functions
If the function you are importing conflicts with an existing name in the program, or if the name of the function is too long, you can alias the function
The syntax is as follows:
from module_name import function_name as mp
The code in the previous section can be expressed as
from pizza import make_pizza as mp mp(16, 'pepperoni') mp(12, 'mushrooms', 'green peppers', 'extra cheese')
Assigning an alias to a module using as
You can also assign an alias to a module in the following syntax:
import module_name as mn
The 8.6.1 code can be rewritten to:
import pizza as mn mn.make_pizza(16, 'pepperoni') mn.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
8.6.5 Import all functions in the module
The syntax is as follows:
from module_name import *
This practice is not recommended and recommended
- Import only the functions you need, not the.Operator
- Import the entire module and call the function with the.Operator
8.7 Function Writing Guide
- Naming functions with lowercase letters and underscores only
- Comments for functions should follow the function definition and be in document string format
- Do not have spaces on either side of the equal sign when specifying a default value for a parameter
8.8 Summary
slightly