From getting started to mastering Python, 100 days is enough—— Cognitive function

Posted by Yesideez on Wed, 29 Dec 2021 12:10:35 +0100


In the previous study, if we need to calculate the factorial of three numbers, we need to write repeated code three times to calculate, which is very troublesome. World class programming master Mr. Martin Fowler once said:“ Code has many bad smells, and repetition is the worst! ". To write high-quality code, the first thing to solve is the problem of repeated code. For the code mentioned at the beginning, we can package the function of calculating factorial into a code block called "function". Where factorial needs to be calculated, we only need to "call function".

Define function

Mathematical functions usually take the form of y = f(x) or z = g(x, y). In y = f(x), f is the name of the function, X is the independent variable of the function, and Y is the dependent variable of the function; In z = g(x, y), G is the function name, X and y are the independent variables of the function, and z is the dependent variable of the function. Functions in Python are consistent with this structure. Each function has its own name, argument and dependent variable. We usually call the argument of a function in Python as the parameter of the function, and the dependent variable as the return value of the function.

In Python, we use the def keyword to define a function. After the keyword space, write the function name. After the function name, write the parameters passed to the function in parentheses, that is, the argument just mentioned, followed by a colon. The code block to be executed (what to do) of a function is also represented by indentation, which is the same as the code block of the previous branch and loop structure. After the function is executed, we will return the execution result of the function through the return keyword, which is the dependent variable of the function we just mentioned. For example:


def add(a, b):
	c = a + b
	return c
	
	
# When using, you can directly enter parameters
print(add(5, 6))    # 11

**Note: * * the whole function needs to be left blank before and after.

Parameters of function

Default value of function

If there is no return statement in the function, the function returns None representing a null value by default. In addition, when defining a function, the function can also have no arguments, but there must be parentheses after the function name. Python also allows function parameters to have default values. If no new parameters are passed in when using a function, the default values are used by default. For example:


# Defines the function of chromophore shaking. n represents the number of chromophores. The default value is 2
import random


def roll_dice(n=2):
    """The chromophore returns the total number of points"""
    total = 0
    for _ in range(n):  # n = 2
        total += random.randrange(1, 6)
    return total

# If no parameter is specified, then n uses the default value of 2, which means shaking two dice
print(roll_dice())      # 8
Variable parameters

We can also implement an add function that sums any number of numbers, because functions in Python language can support variable parameters through asterisk expression syntax. The so-called variable parameter means that 0 or any number of parameters can be passed into the function when calling the function. In the future, when we develop commercial projects in a team way, it is likely to design functions for others to use, but sometimes we do not know how many parameters the caller of the function will pass to the function. At this time, variable parameters can be used. The following code demonstrates the add function of summing any number with variable parameters.

# Use an asterisk expression to indicate that args can receive 0 or any number of parameters
def add(*args):
    total = 0
    # Variable parameters can be placed in a for loop to get the value of each parameter
    for val in args:
        total += val
    return total


# You can pass in 0 or any number of parameters when calling the add function
print(add())               # 0
print(add(1))              # 1
print(add(1, 2))           # 3
print(add(1, 2, 3))        # 6
print(add(1, 3, 5, 7, 9))  # 25

Global and local variables

Global variables (variables not written in any function)
Local variables (variables defined inside a function)
The local variable and global variable in the function are two different variables, which have no relationship with each other and do not affect each other.

Searching for a variable in a Python program is performed in LEGB order:
Local scope - > nested scope - > global scope
- > build in (built-in scope)
If none of the four are found, an error will be reported: NameError: name... not defined

Therefore, we can use global keyword declaration to use global variables or define a local variable to put it into the global scope; nonlocal keyworddeclare variables that use nested scopes (no local variables). Example:

x = 100
def foo():
    x = 200
    print(x)   # Output the value 200 of the local variable x
foo()
print(x)       # Output the value 100 of the global variable x

If I don't want to define the local variable x in the function foo and want to use the global variable x directly, what should I do???
Use global declaration!

x = 100
def foo():
    global x
    print(x)   # Output the value 100 of the global variable x
foo()
print(x)       # Output the value 100 of the global variable x

If I don't want to define the local variable x in the function bar and want to directly use X in the nested scope, what should I do???

x = 100
def foo():
    x = 200
    x = x + 1
    def bar():
        nonlocal x
        x = 300
        print(f'1.{x}')     # 1.300
    bar()
    print(f'2.{x}')         #2.300
foo()
print(x)                    # 100

Manage functions with modules

If there are two identical functions in the same file, problems will easily occur when we call them. However, if the project is developed by team collaboration and multiple people, multiple programmers in the team may have defined a function called foo. In this case, how to solve the naming conflict?
In fact, the answer is very simple. Each file in Python represents a module. We can have functions with the same name in different modules. When using the function, we import the specified module through the import keyword, and then use the call method of fully qualified name to distinguish which module foo function to use. The code is as follows.
module1.py

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

module2.py

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

test.py

import module1
import module2

# Call the function in the mode of "module name. Function name" (fully qualified name),
module1.foo()    # hello, world!
module2.foo()    # goodbye, world!

When importing a module, you can also use the as keyword to alias the module, so that we can use a shorter fully qualified name.

test.py

import module1 as m1
import module2 as m2

m1.foo()    # hello, world!
m2.foo()    # goodbye, world!

In the above code, we import the module that defines the function. We can also use from import... Syntax directly imports the functions to be used from the module. This method can also use the as keyword to alias the module.
test.py

from module1 import foo as f1
from module2 import foo as f2

f1()    # hello, world!
f2()    # goodbye, world!

Functions are packages of code that are relatively independent and reusable. Learn to use definitions and functions, you can write better code. Of course, the standard library of Python language has provided us with a large number of modules and commonly used functions. If we make good use of these modules and functions, we can do more with less code.

Topics: Python Functional Programming