function

  • A function is an organization of code
  • Functions should be able to do a specific job, and generally a function only does one job
  • In some languages, there is a distinction between a function and a procedure. The common interpretation is that a function that returns a result is a function and a procedure that does not return a result. Python makes no distinction
  • Use of functions
    • Function usage needs to be defined first
    • Use functions, commonly known as calls
Define a function
# Only defined words will not be executed
# 1. the def keyword, followed by a space
# 2. The name of the function is defined by itself. The name must follow the naming rules of the order
# 3. Parentheses and colons can not be omitted. Parentheses can have arguments
# 4. Indent all code in a function


def func() :
    print("I'm a function")
    print("Love life")
    
print("The function is done.")
Copy the code
The function is doneCopy the code
# Function call
# write the name of the function directly, followed by the parentheses can not be omitted, the contents of the parentheses are appropriate
func()
Copy the code
I am a function of love lifeCopy the code
# function definition
def func() :
    print('A')
    print('B')
Copy the code
func()
Copy the code
A
B
Copy the code

The parameters and return values of the function

  • Parameters: Responsible for passing some necessary data or information to a function
    • Parameter (formal parameter) : Parameter used in function definition. It has no value and is just a placeholder
    • Arguments (actual arguments) : Values entered when a function is called
  • Return value: an execution result when a function is called
    • Use return to return the result
    • If there is no value to return, return None is recommended to indicate the end of the function
    • The function terminates as soon as it executes return
    • If the function does not have the return keyword, the function returns None by default
# parameter and argument cases
The # person argument is just a symbol
Use another one when calling
def hello(person) :
    print("{}, how are you?".format(person))
    return None
    
p = "Xiao Ming"
To call the function, we need to pass p as an argument
hello(p)
Copy the code
Xiao Ming, how are you?Copy the code
p = "Small five"
hello(p)
Copy the code
Xiao Five, how are you?Copy the code
pp = hello("Small and pure")
print(pp)
Copy the code
Hey, Cheri, how are you? NoneCopy the code
# return case

def hello(person) :
    print("{0}, how are you?".format(person))
    return "Cut short!"
    print(1)
    
p = "Xiao Ming"
rst = hello(p)
print(rst)
Copy the code
Xiao Ming, how are you? End early!Copy the code
Be available to help you at any time
help(None)  Equivalent to help(peint())
Copy the code
Help on built-in function print in module builtins: print(...) print(value, ... , sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.Copy the code
# 99 times table
# version 1.0
for o in range(1.10) :# Control the loop from 1 to 9
    for i in range(1, o + 1) :# inner loop, starting with the first number each time, prints to the same number of lines
        print(o * i, end="")
    print(a)Copy the code
12 4 36 9 48 12 16 5 10 15 20 25 6 12 18 24 30 36 7 14 21 28 35 42 49 8 16 24 32 40 48 56 64 9 18 27 36 45 54 63 72 81Copy the code
help(print)
Copy the code
Help on built-in function print in module builtins: print(...) print(value, ... , sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.Copy the code
# Try using a function to print the multiplication table

def jiujiu() :
    for o in range(1.10) :# Control the loop from 1 to 9
        for i in range(1, o + 1) :# inner loop, starting with the first number each time, prints to the same number of lines
            print(o * i, end="")
        print(a)return None

jiujiu()
jiujiu()
Copy the code
12 4 36 9 48 12 16 5 10 15 20 25 6 12 18 24 30 36 7 14 21 28 35 42 49 8 16 24 32 40 48 56 64 9 18 27 36 45 54 63 72 81 12 4 36 9 48 12 16 5 10 15 20 25 6 12 18 24 30 36 7 14 21 28 35 42 49 8 16 24 32 40 48 56 64 9 18 27 36 45 54 63 72, 81,Copy the code
# change the function above

def printLine(line_num) :
    "' line_num; Print a line representing the line number of the multiplication table.
    for i in range(1, line_num + 1) :print(line_num * i, end="")
        
    print(a)def jiujiu() :
    for o in range(1.10) :# Control the loop from 1 to 9
        printLine(o)
    return None

jiujiu()
Copy the code
12 4 36 9 48 12 16 5 10 15 20 25 6 12 18 24 30 36 7 14 21 28 35 42 49 8 16 24 32 40 48 56 64 9 18 27 36 45 54 63 72 81Copy the code

Parameters,

  • The resources

  • Headfirst Python -> Get started with Python (small turtle), fluent Python -> Exercises

  • Parameters of the classification

    • Common parameter/position parameter
    • The default parameters
    • Keyword parameter
    • Collect parameters
  • Common parameters

    • C See the preceding example

    • Define the variable name directly when defining

    • Calls to put a variable or value directly into the specified location

      Def function name (arguments 1, 2,.....) # Call function name (value1, value2,......) When called, the specific value refers to the position and is assigned by positionCopy the code
  • The default parameters

    • Parameters have default values

    • When called, if no value is assigned to the parameter, the default value is used

      def func_name(p1=v1,p2=v2,........) Func_name () # func_name() value1=100 value2=200Copy the code
  • Keyword parameter

    • grammar

      def func(p1=v1, p2=v2....) Func_body: func_body; func(p1=value1, p2=value2....)Copy the code
    • It’s a hassle, but it has its advantages:

      • It is not easy to confuse. Generally, arguments and parameters only correspond to each other according to their positions, which is prone to error
      • Keyword arguments can be used regardless of their position
  • Collect parameters

  • Put parameters that have no location and cannot correspond to the location of the defined parameter into a specific data structure

  • grammar

    Def func(*args): func_bady: func(p1,p2,p3....)Copy the code
  • The parameter name args is not required, but it is recommended to use args as a convention

  • Parameter name args must be preceded by an asterisk

  • Collection parameters can coexist with other parameters

# Common parameter case

def normal_para(one, two, three) :
    print(one + two)
    return None

normal_para(1.2.3)
Copy the code
3
Copy the code
Default parameter Case 1

def default_para(one, two, three=100) :
    print(one + two)
    print(three)
    return None
    
default_para(1.2)
default_para(1.2.3)
Copy the code
3 3 3 100Copy the code
Default parameter Case 2
# Registration function, need to know the gender of students
# Python students are mostly male. So, if you don't specify when you sign up, we think it's a boy
def reg(name, age, gender="male") :
    if gender == "male":
        print("{0} is {1}, and he is a good student".format(name, age))
    else:
        print("{0} is {1}, and she is a good student".format(name, age))
Copy the code
Call the default argument function case

reg("mingyue".21)

reg("xiaojing".23."female")
Copy the code
mingyue is 21, and he is a good student
xiaojing is 23, and she is a good student
Copy the code
# Keyword parameter Case 1

def keys_para(one, two, three) :
    print(one + two)
    print(three)
    return None

keys_para(one=1, two=2, three=30)

keys_para(three=30, two=2, one=1)
Copy the code
3 30 and 30Copy the code
# Keyword parameter Case 2
def stu(name, age, addr) :
    print("I am a student")
    print("My name is {0}, I am {1} years old, AND I live {2}".format(name, age, addr))
    
n = "jingjing"
a = 18
addr = "My home"

# Common parameters, pass only by position, error prone
stu(a, n, addr)

def stu_key(name="No name", age=0, addr="No addr") :
    print("I am a student")
    print("My name is {0}, I am {1} years old, AND I live {2}".format(name, age, addr))
    
n = "jingjing"
a = 18
addr = "My home"

# Common parameters, pass only by position, error prone
stu_key(name=n, age=a, addr=addr)
Copy the code
I am a student. My name is jingjing. I am a studentCopy the code
Collect parameter cases
# The function simulates a student introducing himself, but the details are not clear
# args think of it as a List
def stu( *args) :
    print("Hello everyone, LET me introduce myself, just a few words:")
    The # type function checks the type of a variable
    print(type(args))
    for item in args:
        print(item)


stu("Liuying".18."Datongzhou District, Beijing"."wangxiaojing"."single")

stu("Zhou Da Shen")
Copy the code
<class 'tuple'> Liuying 18 Beijing Dadongzhou district wangxiaojing single Hello everyone, I introduce myself, simple say two sentences: <class 'tuple'> <class 'tuple'Copy the code
Collect parameter cases
The collection parameter can be called without any arguments. The collection parameter is an empty tuple
stu()
Copy the code
<class 'tuple'> <class 'tuple'>Copy the code
# If called with keyword argument format, there is a problem
stu(name="Liuying")
Copy the code

Collect parameters keyword Collect parameters

  • Store keyword arguments in dictionary format as collection parameters

  • Grammar:

    Def func(**kwargs): func_body #; func(p1=v1, p2=v2, p3=v3....)Copy the code
  • Kwargs are generally accepted

  • When called, put extra keyword arguments into kwargs

  • Accessing Kwargs requires access in dictionary format

Collect parameter cases
# Self-introduction
Call with keyword argument
def stu( **kwargs) :
    # Use of kwargs in a function body without an asterisk
    print(Hello everyone, LET me introduce myself first:)
    print(type(kwargs))
    Python2 differs from Python3 for dictionary access
    for k,v in kwargs.items():
        print(k, "-", v)

stu(name="Liuying", age=19, addr="Datongzhou District, Beijing" , lover="Wang Xiaojing", work="Teaccher")

print("*" * 50)

stu(name="Zhou Da Shen")
Copy the code
Let me introduce myself first. <class 'dict'> name -- Liuying age -- 19 addr -- Beijing Datong Zhou Lover-Wang Xiaojing work-teaccher * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Hello everybody is good, let me introduce myself: < class > 'dict' name - weeks, a great godCopy the code
Collection parameters can be empty cases
stu()
Copy the code
<class 'dict'>Copy the code

Collect the order of arguments mixed calls

  • Collection parameters, keyword parameters, and common parameters can be mixed
  • The rules of use are. Common and keyword parameters are preferred
  • When defining parameters, find common parameters, keyword parameters, collect parameters tuple and dict
Collect parameter mixed call cases
# STU simulates a student's self-introduction
def stu(name, age,  *args, hobby="没有", **kwargs) :
    print("Hello, everybody.")
    print("My name is {0} and I am {1} years old.".format(name, age))
    if hobby == "没有":
        print("I don't have a hobby, so sorry")
    else:
        print("My hobby is {0}".format(hobby))
        
    print("*" * 20)
    
    for i in args:
        print(i)
        
    print("#" * 30)
    
    for k,v in kwargs.items():
        print(k, "-", v)
        
Start calling the function
name = "Liuying"
age = 19

# Different formats for calls
stu(name, age)

stu(name, age, hobby="Swimming")

stu(name, age, "Wang Xiaojing"."Stone Liu", hobby="Swimming", hobby2="Cooking", hobby3="Talking to different girls.")
Copy the code
My name is Liuying. I am 19 years old. I don't have hobbies, so sorry * * * * * * * * * * * * * * * * * * * * # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # well, hi, Hello My name is Liuying, I this year 19 years old. My hobby is swimming * * * * * * * * * * * * * * * * * * * * # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # well, hi, Hello My name is Liuying, I this year 19 years old. My hobby is swimming * * * * * * * * * * * * * * * * * * * * xiao-jing wang Liu stone # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # hobby2 - cooking hobby3 - chat with different girlsCopy the code

Collecting parameter unpacking problem

  • Put parameters into a List or dictionary, and directly put values from a List/dict into collection parameters
  • Grammar: Reference case
Unpacking of collection parameters

def stu( *args) :
    print("Ha ha ha ha.")
    # n is used to indicate the number of cycles
    # mainly used for debugging
    n = 0
    for i in args:
        print(type(i))
        print(n)
        n += 1
        print(i)
        
# stu("Liuying", "Wangxiaojing", 19, 20)

l = ["Liuying".19.20."Wangxiaojing"]

stu(l)
Args = (["Liuying", 19, 23, "Wangxiaojing",])
# Obviously goes against our original idea

We need to unpack the symbol, that is, the call is preceded by an asterisk
stu(*l)
Copy the code
<class 'list'> 0 ['Liuying', 19, 20, <class 'STR '> 0 Liuying <class 'int'> 1 19 <class 'int'> 2 20 <class' STR '> 3 WangxiaojingCopy the code

Similarly, dict collection parameters can be unpacked, but

  • Unpack the dict type
  • You need to unpack with two asterisks

Function of the document

  • The function documentation provides reference information about the use of the current function
  • The document is written as follows:
    • The first line at the beginning of the function uses the triple quoted string definition
    • It usually has a specific format
    • Refer to the case
  • Document view
    • Use a help function of the form help(func)
    • Using __doc__, view the case
# Document case

def stu(name, age, *args) :
    This is row 1 this is row 2 this is row 3
    print("This is hanshu stu")
    pass
Copy the code
View the function documentation
help(stu)
stu.__doc__
Copy the code
Help on function stu in module __main__: stu(name, age, *args) __main__: stu(name, age, *args) __main__: stu(name, age, *args)Copy the code
def stu(name, age) :
    Param name: indicates the student's name: Param age: indicates the student's age: return: This function does not return ""
    pass

print(help(stu))

print("*" * 20)

print(stu.__doc__)

Copy the code
Help on function stu in module __main__: stu(name, age) __main__: stu(name, age) __main__: stu(name, age) None ******************** :param name: indicates the student's name: Param age: indicates the student's age: return: This function does not return a valueCopy the code