"Python programming from entry to practice" function def knowledge

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/xue_yanan/article/details/86626604

# Define function format, such as:

def greet_user():

    print("Hello!")

greet_user()

 

# Pass information to a function, such as:

def greet_user(username):

    print("Hello, "+username.title())

greet_user("rose")

 

# Arguments and parameters. Parameter is a function of the information needed to complete their work. Argument is passed to the function information of the function is called. In the above example parameter is the username, rose is argument.

Position # arguments: the same order of arguments required and formal parameters. such as:

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")

# Call the function multiple times

describe_pet("dog","tony")

 

# Keyword arguments: the name is passed to the function - value pairs. Without regard to the order of the arguments in the function call, also clearly pointed out the use of a function call in the respective values. such as:

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(pet_name="lucy",animal_type="cat")

 

# Default: for each parameter can specify a default value. When the call to the function parameter arguments provided, Python be specified argument values; otherwise, the default value of parameter. Therefore, to specify a default parameter value, the function may be

# Call the appropriate arguments omitted. Note: When using the default value, there is no need to list the default parameter values ​​in the parameter list, and then lists the parameter has a default value, allowing better understand the location parameters python. such as:

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("xiha")

describe_pet(pet_name="wangcai")

describe_pet("hurry","hamster")

describe_pet(pet_name="lucy",animal_type="cat")

describe_pet(animal_type="panda",pet_name="panpan")

 

# Return Value: display output function is not always directly, instead, it can handle some data, and returns a value or set. In the function, use the return statement to return values ​​to the calling function line. such as:

"" "Defined functions get_formatted_name () parameter accepted by first and last name" ""

def get_formatted_name(first_name, last_name):

     "" "The combined first and last names stored in the variable full_name in" ""

    full_name = first_name+" "+last_name

    "" "Full_name convert the value of a capitalized first letter format, the results are returned to the function call line." ""

    return full_name.title()

"" "Call return value of the function will return the value stored in the variable musician in" ""

musician = get_formatted_name("Jimi", "Hendrix")

"" "Output variable musician" ""

print(musician)

 

# Make arguments become optional. such as:

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)

 

# Return to the dictionary, such as:

def build_person(first_name, last_name, age=""):

    "" "Return a dictionary" ""

    person = {"first": first_name, "last": last_name}

    if age:

        person["age"]=age

    return person

musician=build_person("jimi","hendrix", age=27)

print(musician)

 

# Function while loop combination, such as:

def get_formatted_name(first_name, last_name):

    full_name = first_name+" "+last_name

    return full_name.title()

while True:

    print("Please tell me your name(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

musician = get_formatted_name(f_name,l_name)

print("Hello "+musician+" !")

 

# Transfer list, for example;

def greet_user(names):

    for name in names:

        print(name)

user_names=["rose",'jack','tony']

greet_user(user_names)

 

# List of changes in functions, such as:

def print_models(unprinted_designs,completed_models):

    """

    Each print design simulation until there are no print design

    After printing each design, will move to list completed_models

    """

    while unprinted_designs:

        current_design = unprinted_designs.pop()

        print("Printing model: "+current_design)

        completed_models.append(current_design)

def show_completed_models(completed_models):

    print("The following models have been printed:")

    for completed_model in completed_models:

         print(completed_model)

"""

robot pendant: robot pendants;

dodecahedron: dodecahedron

"""

unprinted_designs = ["iphone case", "robot pendant", "dodecahedron"]

completed_models = []

print_models(unprinted_designs, completed_models)

show_completed_models(completed_models)

 

# Pass any number of arguments, such as:

def make_pizza(*toppings):

    "" "Parameter names in the asterisk * toppings allow python to create an empty tuple named toppings, and all values ​​are encapsulated in this tuple" ""

    print("Making a pizza with the following toppings:")

    for topping in toppings:

        print(topping)

make_pizza("pepperoni")

make_pizza("mushrooms", "green peppers", "extra cheese")

 

# Combined with any number of positions and arguments arguments, such as:

# Note: If you want to accept the different types of function arguments, the function definition will be received in any number of arguments on the last parameter. first matching position python keyword arguments and argument, then the remaining arguments are collected in the last parameter.

def make_pizza(size ,*toppings):

    print("Make a "+str(size)+"-inch pizza with the following toppings:")

    for top in toppings:

        print(top)

make_pizza(16, "pepperoni")

make_pizza(12, "mushrooms", "green peppers", "extra cheese")

 

# Any number of keyword arguments, such as:

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)

 

# The function is stored in the module: using import statements allow the use of code modules in the program files currently running. such as:

"" "Create a file called make_pizzas.py in the directory pizza.py located, write the following code:" ""

def make_pizza(size,*toppings):

    print("Make a "+str(size)+"-inch pizza with the following toppings:")

    for top in toppings:

        print(top)

 

"" "Import module pizza just created, call make_pizza twice." ""

import pizza

pizza.make_pizza(16, "pepperoni")

pizza.make_pizza(12, "mushrooms", "green peppers", "extra cheese")

"""

How it works: When python read the file, so that lines of code import pizza python open the file pizza.py, and in which all functions are copied into this program.

Call the method: the module name function name ()

"""

 

# Module in which a plurality of functions, specific functions can be introduced, introducing follows:

"""

Fast import module name from the function name

from pizza import make_pizza,make_pizza1,make_pizza2

"""

# Use as an alias to the function, for example:

from pizza import make_pizza as mp

mp(16, "pepperoni")

mp(12, "mushrooms", "green peppers", "extra cheese")

 

# Use as an alias to the module, such as:

import pizza as p

p.make_pizza(16, "pepperoni")

p.make_pizza(12, "mushrooms", "green peppers", "extra cheese")

 

# Import module all function

from pizza import *

make_pizza(16, "pepperoni")

make_pizza(12, "mushrooms", "green peppers", "extra cheese")

 

Guess you like

Origin blog.csdn.net/xue_yanan/article/details/86626604
Recommended