Introduction to Python Xiaobai: Summary of super-detailed knowledge points about functions (definition, passing parameters, return values, modules, etc.)

1. Define the function

Functions are defined using the def keyword.

def functionName():

def great_user(username):
    print(f"{
      
      username.title()},hello!")

great_user("jessi")

insert image description here

Actual and Formal Parameters

  • Actual parameter (argument) : In the code greet_user('jesse'), the value 'jesse' is an actual argument, that is, the information passed to the function when calling it.
  • Formal parameter (parameter) : In the definition of the function greet_user(), the variable username is a formal parameter, that is, the information required by the function to complete the work.

When calling a function, enclose the information you want the function to use within parentheses. In greet_user('jesse'), the actual parameter 'jesse' is passed to the function greet_user(), and this value is assigned to the formal parameter username.

Second, pass the actual parameters

2.1 Positional arguments

When calling a function, Python must associate each actual parameter in the function call with a formal parameter in the function definition. For this purpose, the simplest way of associating is based on the order of the actual parameters. This type of association is called a positional argument .

def describie_pet(animal_type,pet_name):
    print(f"I have a {
      
      animal_type}.")
    print(f"My {
      
      animal_type}'s name is {
      
      pet_name.title()}")

describie_pet('hamster','harry')
describie_pet('dog','willie')

insert image description here

When calling a function with positional arguments, the arguments must be in the correct order.

2.2 Keyword arguments

Keyword arguments are name-value pairs passed to the function, and the order does not matter at this point.

  • When using keyword parameters, the formal parameter names in the function definition must be specified exactly.
def describie_pet(animal_type,pet_name):
    print(f"I have a {
      
      animal_type}.")
    print(f"My {
      
      animal_type}'s name is {
      
      pet_name.title()}")

describie_pet(animal_type='hamster',pet_name='harry')
describie_pet(pet_name='willie',animal_type='dog')

insert image description here

2.3 Default values

When writing a function, you can assign default values ​​to each parameter.

  • When an actual parameter is provided to the formal parameter in the calling function, Python will use the specified actual parameter value;
  • Otherwise, the default value of the formal parameter is used.
def describie_pet(animal_type,pet_name='winnie'):
    print(f"I have a {
      
      animal_type}.")
    print(f"My {
      
      animal_type}'s name is {
      
      pet_name.title()}")

describie_pet(animal_type='hamster',pet_name='harry')
describie_pet('dog')

insert image description here

practice questions

insert image description here

the code

def make_shirt(size,text):
    print(f"The shirt's size is {
      
      size} and the text will be printed on it is {
      
      text.title()}")

def make_shirt_default(size='XL',text = 'I love Python'):
    print(f"The shirt's size is {
      
      size} and the text will be printed on it is {
      
      text.title()}")

    
print('8-3')
make_shirt('M','make everyday counts')
make_shirt(size='L',text='time is money')

print('8-4')
make_shirt_default()
make_shirt_default(size='M')
make_shirt_default(text='I am the best')

output

insert image description here

3. Return value

3.1 Returning simple values

Use the return keyword to return the function result when defining a function, and use a variable to receive the return result of the function when using the function.

def get_name(first_name,last_name):
    full_name = f"{
      
      first_name} {
      
      last_name}"
    return full_name.title()

musician = get_name('jimi','ma')
print(musician)

insert image description here

3.2 Optional arguments

Give the formal parameter a default null value, and then use the conditional statement in the function, so that the function can be used when the user uses the formal parameter and does not apply to the formal parameter.

  • Optional values ​​allow functions to handle a variety of different situations while keeping function calls as simple as possible.
def get_formatted_name(first_name,last_name,middle_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('jimi','ma')
print(musician)
musician_1 = get_formatted_name('will','hooker','lee')
print(musician_1)

insert image description here

3.3 return dictionary

Functions can return complex data types such as lists and dictionaries.

def build_person(first_name,last_name,age=None):
    person = {
    
    'first_name':first_name,'last_name':last_name}
    if age:
        person['age'] = age
    return person

musician = build_person('jimi','hendrix',27)
print(musician)
  • In the code, age is an optional formal parameter, and the set value is None, which is a placeholder.

insert image description here

Usage of None value : Detailed explanation of none value

  • In conditional tests, a value of None is equivalent to False
  • None is an empty value, which is a special value in Python, represented by None. None can be assigned to any variable
  • None is a special empty object that can be used as a placeholder
  • None is not equal to an empty string, empty list, 0, or False

3.4 Using while loops in functions

def get_formatted_name(first_name, last_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

    format_name = get_formatted_name(f_name,l_name)
    print(f"Hello, {
      
      format_name}!")

insert image description here

practice questions

the code

insert image description here

def city_country(city,country):
    return f"{
      
      city.title()},{
      
      country.title()}"


def make_album(name,singer,num_songs = None):
    album = {
    
    'name':name,'singer':singer}
    if num_songs:
        album['number of songs'] = num_songs
    return album

print('8-6')
print(city_country('zibo','china'))
print(city_country('florence','italy'))
print(city_country('madrid','spain'))

print('8-7')
print(make_album('love and peace','jack',5))
print(make_album('nature','diane'))

print('8-8')
while True:
    print("Enter the singer and album's name(enter q to exit)")
    singer = input("Enter the singer: ")
    if singer == 'q':
        break
    name = input("Enter the album name: ")
    if name == 'q':
        break
    album = make_album(name,singer)
    print(f"The album's name is {
      
      album['name'].title()} and the singer is {
      
      album['singer'].title()}")

output

insert image description here

4. Delivery list

Pass the list as an argument in the function.

def greet_users(names):
    for name in names:
        print(f"Hello,{
      
      name.title()}!")

username = ['hannah','will','grace']
greet_users(username)

4.1 Modifying lists in functions

Complete the modification of the list in the function, and define a function to complete the output of the list elements.

def print_models(unprinted_models, completed_models):
    while unprinted_models:
        current_design = unprinted_models.pop()
        print(f"Printing model: {
      
      current_design}")
        completed_models.append(current_design)

def show(completed_models):
    print('The following models have been printed:')
    for completed_model in completed_models:
        print(completed_model)

unprinted_models = ['phone case','robot pendant','dodecahedron']
completed_models = []
print_models(unprinted_models,completed_models)
show(completed_models)

insert image description here

4.2 Prohibited function modification list

If you don't want the function to modify the contents of the list, you can pass a copy of the list to the function. This will only modify the copy of the list, but the original list content will not be affected.

Create a copy of the list:

How to copy a list

  1. Slicing: list1 = list0 [ : ]
  2. Use the copy function: list1 = list0.copy()
  3. Use the list function: list1 = list(list0)
def print_models(unprinted_models, completed_models):
    while unprinted_models:
        current_design = unprinted_models.pop()
        print(f"Printing model: {
      
      current_design}")
        completed_models.append(current_design)

def show(completed_models):
    print('The following models have been printed:')
    if completed_models==[]:
        print("This list is empty")
    else:
        for completed_model in completed_models:
            print(completed_model)

unprinted_models = ['phone case','robot pendant','dodecahedron']
completed_models = []
print_models(unprinted_models[:],completed_models)
show(unprinted_models)
show(completed_models)

You can see that the elements of the unprinted_models list have not been changed due to the use of a copy of the unprinted_models list.

insert image description here

practice questions

insert image description here

the code

def show_message(text):
    for t in text:
        print(f"{
      
      t.title()}")

def send_message(text1,text2):
    while text1:
        t = text1.pop()
        print(f"{
      
      t.title()}")
        text2.append(t)

def print_list(list1):
    if list1 == []:
        print("This is an empty list.")
    else:
        for l in list1:
            print(f"{
      
      l.title()}")

print('8-9')
text = ['hello','good morning','goodbye','thank you']
show_message(text)

print('8-10')
text1 = ['hello','good morning','goodbye','thank you']
text2=[]
send_message(text1,text2)
print_list(text1)
print_list(text2)

print('8-11')
text1 = ['hello','good morning','goodbye','thank you']
text2=[]
send_message(text1[:],text2)
print_list(text1)
print_list(text2)

output

insert image description here

5. Pass any number of arguments

  • Applicable situation: when the function does not know how many actual parameter values ​​​​to receive

Adding an asterisk * in front of the formal parameter tells Python to create an empty tuple named the formal parameter and pack all the values ​​received by the function into the tuple.

At this point you can have the function take any number of arguments.

def method(*value)

The following code will print different types of pizzas. Because we don’t know how many kinds of pizzas need to be made, we set different toppings as unknown quantities. When calling the function, we can add an unknown number of pizza toppings, and these toppings will be stored in a in the tuple .

def make_pizza(*toppings):
    print("\nMaking a pizza with the following toppings:")
    for topping in toppings:
        print(f"{
      
      topping.title()}")

make_pizza('pepperroni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

insert image description here

5.1 Combinations of positional arguments and any number of arguments

  1. If you want the function to accept different types of arguments, you need to put the formal parameter that accepts any number of arguments last .
  2. Python first matches the positional and keyword arguments, and then collects the remaining arguments into the last formal parameter tuple .

The storage format is as follows:

insert image description here

def make_pizza(size,*toppings):
    print(f"\nMaking a {
      
      size}-inch pizza with the following toppings:")
    for topping in toppings:
        print(f"{
      
      topping.title()}")

make_pizza(12,'pepperroni')
make_pizza(16,'mushrooms', 'green peppers', 'extra cheese')

insert image description here

5.2 Using any number of keyword arguments

Let the function receive arbitrary key-value pairs: use the double asterisk ** parameter name to let Python create an empty dictionary named the parameter name, and put all the key-value pairs received into the dictionary.

def method ( arg1, arg2, **info )

insert image description here

Python will create a dictionary named info for the function and store all the key-value pairs in it.

def build_profile(first_name,last_name,**user_info):
    user_info['first_name'] = first_name
    user_info['last_name'] = last_name
    return  user_info
user_profile = build_profile('amy','ma',city = 'zibo',age = 28,major='computer and science')
print(user_profile)

Debug the above code, you can see that the created dictionary contains 5 key-value pairs, and you can see that the order of the key-value pairs in the dictionary is to define the key-value pairs you input in the function first, and then define the key-value pairs in the function Formal parameters.

insert image description here

The output is shown below.

insert image description here

practice questions

insert image description here

the code

def make_pizza(*toppings):
    for topping in toppings:
        print(f"The pizza is made of {
      
      topping.title()}")

def build_profile(f_name,l_name,**info):
    info['first name'] = f_name
    info['last name'] = l_name
    return info

def make_car(maker,type,**info):
    info['maker'] = maker
    info['type'] = y=type
    return info


print('8-12')
make_pizza('1')
make_pizza('2','3')
make_pizza('34')

print('8-13')
my_profile = build_profile('weiyi','ma',city = 'zibo',major = 'cs', university = 'SHU')
for k,v in my_profile.items():
    print(f"My {
      
      k.title()} is {
      
      v.title()}")

print('8-14')
car = make_car('subaru', 'outback', color='blue', tow_package=True)
print(car)

output

insert image description here

6. Store functions in modules

Functions can be stored in separate files called modules , which are then imported into the main program.

  • The import statement allows code from a module to be used in the currently running program file.

6.1 Import the entire module file

Syntax: import module-name

1. Create a module: pizza.py is a file containing the make_pizza function.

insert image description here

2. Call the module: call the make_pizza module in main.py.

Syntax: module_name.function_name()

  • When Python reads this file, use import pizza to have Python open the file pizza.py.
  • To call a function in the imported module, use the name of the imported module pizza.function name make_pizza() to call

insert image description here

6.2 Import specific functions in modules

语法: from module_name import function_name

Separate function names with commas: import any number of functions from a module:

语法:from module_name import function_0, function_1, function_2

from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

6.3 Use as to assign an alias to a function

When the function name is too long, you can use the as keyword to give it an alias.

语法:from module_name import function_name as fn

from pizza import make_pizza as mp

mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')

6.4 Use as to assign an alias to the module

Syntax: import module_name as mn

import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

6.5 Import all functions in a module

Syntax: from module_name import *

from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

Guess you like

Origin blog.csdn.net/weixin_45662399/article/details/132143990
Recommended