Python100Days study notes --- use Day6 functions and modules

Before explaining the contents of this chapter, we'll examine a math problem, say the following equation How many positive integer solutions.

x 1 + x 2 + x 3 + x 4 = 8 x_1 + x_2 + x_3 + x_4 = 8

In fact, the above problem is equivalent to 8 divided into four sets of apple Apple at least a number of kinds of programs. Think of this question the answer is pretty clear.

Here Insert Picture Description
Program can be used to calculate the Python value, as shown in the code below.

"""
输入M和N计算C(M,N)

Version: 0.1
Author: 骆昊
"""

m = int(input('m = '))
n = int(input('n = '))
fm = 1
for num in range(1, m + 1):
    fm *= num
fn = 1
for num in range(1, n + 1):
    fn *= num
fmn = 1
for num in range(1, m - n + 1):
    fmn *= num
print(fm // fn // fmn)

Function returns
do not know if you noticed, in the above code, we do three times factorial, this code is actually duplicate code. The master programmer Mr. Martin Fowler once said: "There are many bad taste codes, repetition is the worst kind!", To write high-quality code first problem to be solved is to repeat the code. For the above codes, we can calculate the factorial function call encapsulated into a "function" function modules, where needed factorial calculation, we only need to "call" the "function" on it.

Defined functions
can be used in Python def keyword to define functions and variables as each function also has a famous name, but naming with variable naming conventions are consistent. Can be passed in parentheses after the function name placed to function parameters, function and math on this is very similar in function parameters of the program is equivalent to saying the mathematical argument of a function, and the function execution is complete we can by return keyword to return a value, which is equivalent to saying that the dependent variable mathematical functions.

In the understanding of how to define a function, we can carry out the reconstruction of the above code, the so-called reconstruction is without effect on the structure of the code to adjust the premise of code execution result, the code after reconstruction is shown below.

def factorial(num):
    """求阶乘"""
    result = 1
    for n in range(1, num + 1):
        result *= n
    return result


m = int(input('m = '))
n = int(input('n = '))
# 当需要计算阶乘的时候不用再写循环求阶乘而是直接调用已经定义好的函数
print(factorial(m) // factorial(n) // factorial(m - n))

Description : Python's math module is already a factorial function, in fact, can be used directly to calculate the factorial function without this ready-made their own definition. The following examples are some of the functions in Python are also readily available, we are here to explain the definition and use of the function and only then they realized again, the actual development is not recommended to do this low-level repetitive work.

Function parameters
function is a code that the vast majority of programming languages are supported by the "building blocks", but the Python function with other functions of language is not the same there are still many places where a significant difference is for Python processing function parameters. In Python, function parameters can have default values, but also supports the use of variable parameters, so Python does not need to be like other languages support function overloading, because we can make it in a variety of different definitions of a function of time use, the following are examples of two small.

from random import randint


def roll_dice(n=2):
    """摇色子"""
    total = 0
    for _ in range(n):
        total += randint(1, 6)
    return total


def add(a=0, b=0, c=0):
    """三个数相加"""
    return a + b + c


# 如果没有指定参数那么使用默认值摇两颗色子
print(roll_dice())
# 摇三颗色子
print(roll_dice(3))
print(add())
print(add(1))
print(add(1, 2))
print(add(1, 2, 3))
# 传递参数时可以不按照设定的顺序进行传递
print(add(c=50, a=100, b=200))

We give two functions above parameters are set to default values, which means that if you use the default value for this parameter if the value of the corresponding parameter no incoming call functions, so we in the above code They can use a variety of different ways to add function calls, which like many other languages ​​function overloading effect is the same.

In fact, the above add function as well as a better implementation, because we could have zero or more parameters adder, and specifically how many parameters are determined by the caller, we function as a designer this point know nothing, so uncertain when the number of parameters, we can use a variable parameter, the code shown below.

# 在参数名前面的*表示args是一个可变参数
def add(*args):
    total = 0
    for val in args:
        total += val
    return total


# 在调用add函数时可以传入0个或多个参数
print(add())
print(add(1))
print(add(1, 2))
print(add(1, 2, 3))
print(add(1, 3, 5, 7, 9))

Management module with functions
for any programming language, to variables, functions such identifiers from the names are a vexing problem, because we will encounter this naming conflict awkward situation. The simplest scenario is the definition of the two functions of the same name in the same .py file, since Python has no concept of function overloading, then before the latter definition will cover the definition, it means that the two functions are actually a function of the same name only one is present.

def foo():
    print('hello, world!')


def foo():
    print('goodbye, world!')


# 下面的代码会输出什么呢?
foo()

Of course, the above case we can easily be avoided, but if it is time to carry out the project developed by a team of more than collaboration, the team may have more programmer defines a function named foo, then how to solve this naming conflict it? The answer is very simple, Python each file represents a module (module), we can have a function with the same name in different modules, when using the function we imported by import keyword specified module can be distinguished in the end which module using function foo, the code looks like.

module1.py

def foo():
    print('hello, world!')

module2.py

def foo():
    print('goodbye, world!')

test.py

from module1 import foo

# 输出hello, world!
foo()

from module2 import foo

# 输出goodbye, world!
foo()

Manner may be distinguished as shown in the end use to which a function foo.

test.py

import module1 as m1
import module2 as m2

m1.foo()
m2.foo()

However, if the code is written in the following way, the program is called in the last foo import, because the import foo foo covered previously imported.

test.py

from module1 import foo
from module2 import foo

# 输出goodbye, world!
foo()

test.py

from module2 import foo
from module1 import foo

# 输出hello, world!
foo()

It should be noted that, if we import the module in addition to the definition of the function also can execute code in there, then the Python interpreter will execute the code when you import the module, in fact, we may not hope so, so if we executing code modules written, it is preferable to execute this code into the condition as shown below, so unless directly run the module, if the code under conditions will not be implemented, because of the direct execution module only name is the " main ."

module3.py

def foo():
    pass


def bar():
    pass


# __name__是Python中一个隐含的变量它代表了模块的名字
# 只有被Python解释器直接执行的模块的名字才是__main__
if __name__ == '__main__':
    print('call foo()')
    foo()
    print('call bar()')
    bar()

test.py

import module3

# 导入module3时 不会执行模块中if条件成立时的代码 因为模块的名字是module3而不是__main__

Here Insert Picture Description

Here Insert Picture Description

Here Insert Picture Description

Here Insert Picture Description

Note: You can see by the above procedures, when we repeated the code and relatively independent function to extract a function, we can combine these functions to solve more complex problems, which is why we need to define and use a very important function of reason.

Finally, we discuss issues related Python variable scope.

def foo():
    b = 'hello'

    # Python中可以在函数内部再定义函数
    def bar():
        c = True
        print(a)
        print(b)
        print(c)

    bar()
    # print(c)  # NameError: name 'c' is not defined


if __name__ == '__main__':
    a = 100
    # print(b)  # NameError: name 'b' is not defined
    foo()

The code above can be successfully executed and prints out 100, hello and True, but we have noticed, does not define a and b are two variables within the function bar, then a and b are from. If we define a branch in the code above in a variable a, which is a global variable (global variable), belongs to the global scope, because it is not defined in any one function. In the above, we define the function foo variable B, which is a local variable (local variable) in the function definition, belong to the local scope, and external function foo not have access to it; however, the internal function foo bar function, the variable b belongs nested scopes, we are in the bar function can access it. The variable in a bar belonging c local scope, in addition to the function bar is not accessible. In fact, the order of "local scope", "nested scopes" when Python looks for a variable "global scope" to search and order "built-scope", the first three we've seen in the above code to the so-called "built-scope" is a built-in Python those identifiers, we previously used input, print, int belong to the built-in scope.

Look at the following piece of code, we want to modify the value of a global variable by a function call, but in fact the following code is not.

def foo():
    a = 200
    print(a)  # 200


if __name__ == '__main__':
    a = 100
    foo()
    print(a)  # 100

After you call the function foo, we still find that the value of a 100, this is because when we write a = 200 in the function foo, the re-definition of a name for a local variable, it is with a global scope not the same variable, because of their variable a local scope, and therefore no longer search function foo global scope of a. If we want to modify global in scope foo function, a, the code shown below.

def foo():
    global a
    a = 200
    print(a)  # 200


if __name__ == '__main__':
    a = 100
    foo()
    print(a)  # 200

We can use the global keyword to indicate that the function foo the variable from a global scope, if not a global scope, then the following line of code will define variables and place a global scope. Similarly, if we want the function inside the function can modify the variable nested scopes, you can use the keyword to indicate nonlocal variables from nested scopes, please self-test.

In the actual development, we should minimize the use of global variables, modify and use unexpected because the scope and impact of global variables is too wide, may occur, in addition to a global variable has a longer than local variable life cycle, the memory occupied by objects could result in a long time can not be garbage. In fact, reduce the use of global variables, it is also an important measure to reduce the degree of coupling between the code, but also the practice of Demeter. Reduce the use of global variables means we should try to make the scope of variables inside a function, but if we want a local variable life cycle extension, so that in the end it's the definition of a function call you can still use its value this time we need to use a closure, which we explain in subsequent content.

Description : Many people will often "closure" and "anonymous function" confused, but in fact they are not the same thing, if you want to understand this concept, you can take a look at Wikipedia or the knowledge of the discussions on the concept of peace .

He said so much, in fact, the conclusion is simple, we can write Python code from now on in the following format, this little bit of improvement in our understanding is actually a huge step forward in the basic functions and scope.

def main():
    # Todo: Add your code here
    pass


if __name__ == '__main__':
    main()
Published 124 original articles · won praise 141 · views 160 000 +

Guess you like

Origin blog.csdn.net/weixin_36838630/article/details/105205932