python Learning: Functions (a)

For example:

def greet_user():
    """显示简单的问候语"""
    print("Hello!")

greet_user()

First, the function definition:

1, using the keyword: def to define a function of a python.

2, function name: greet_user for the function name. In python using an underscore "_" to separate different words, instead of using java commonly used hump representation.

3, function parameters: the function parameter is added in parentheses after the function name.

4, the end of the function is defined: a colon ":" to the end.

5, the body functions: as a function of the body after the colon. Body of the function requires the use of indentation to distinguish whether the body of the function, rather than the way to use parentheses to define.

6, the document string: three pairs of double quotes the document character string (the docstring of), the purpose of marking function.

Second, the transmission parameters:

1, delivery location arguments: arguments and parameters required position consistent.

2, pass keywords arguments: each parameter configured by the variable name and value.

3, you can also use the lists and dictionaries.

4, the default values: for each parameter may be assigned a default value of a function definition, if the function call is not assigned to the parameter, the default value.

                     Note that the default value must (may be a plurality) in the back.

Location argument:

def describe_pet(animal_type, pet_name):
    """显示宠物的信息"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet('hamster', 'harry')

Keyword argument:

def describe_pet(animal_type, pet_name):
    """显示宠物的信息"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet(animal_type='hamster', pet_name='harry')

Third, the return value:

You can use the return statement to return values ​​to the line of code that calls the function.
 

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', 'lee')
print(musician)

Fourth, the transfer list:

def greet_users(names):
    """向列表总的每位用户都发出简单的问候"""
    print()
    for name in names:
        msg = "Hello, " + name.title() + "!"
        print(msg)

usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)

Fifth, the function list of modifications:

def print_models(unprinted_designs, completed_models):
    """
    模拟打印每个设计, 直到没有未打印的设计为止
    打印每个设计后, 都将其移到列表completed_models中
    """
    while unprinted_designs:
        current_design = unprinted_designs.pop()

        #模拟根据设计制作3D打印模型的过程
        print("Printing model:" + current_design)
        completed_models.append(current_design)

def show_completed_models(completed_models):
    """显示打印好的所有模型"""
    print("\nThe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)

unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []

print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)

Sixth, prohibition function to modify the list:

A copy rather than the original list that can be passed to the function to achieve the ban function to modify the list.

Use python slice listname [:] to create a copy.

print_models(unprinted_designs[:], completed_models)

Seven, pass any number of arguments:

def make_pizza(*toppings):
    """概述要制作的比萨"""
    print("\nMaking a pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

Where the asterisk * toppings to make Python creates an empty tuple named toppings, and all values ​​are encapsulated to receive this tuple.

The Python argument packaged into a tuple, even when only a receive function value is also true.

Eight, in conjunction with any number and position of the argument arguments:

If you want to accept the different types of function arguments, you must accept any number of arguments in a function definition of shape parameter on the last . Python first argument and keyword matching position argument, then the remaining arguments are collected in the last parameter.
 

def make_pizza(size, *toppings):
    """概述要制作的比萨"""
    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')

Nine, any number of keyword arguments:

def build_profile(first,last,**user_info):
    """创建一个字典,其中包含我们所知道的有关用户的一切"""
    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 = 'princeton',
                                field = 'physics')
print(user_profile)

Where: parameter ** user_info two asterisks let empty dictionary Python create a named user_info all names and received - the value of all packaged into this dictionary.

Released four original articles · won praise 3 · Views 368

Guess you like

Origin blog.csdn.net/Wolfswood/article/details/104344476