These simple functions in Python, you won't be embarrassed any more

Keywords: Programming Python network

1, function

The function in Python is a code segment for realizing a certain function, which can be reused.

That is, don't build the wheel again. Use the function when you meet the scene, that is, functional programming

Next, I define a my func, pass in a Hello World, and print a Hello World

def my_func(message):
    print('Got a message: {}'.format(message))
​
# Call the function my func ()
my_func('Hello World')
# output
Got a message: Hello World

Simple knowledge points

  • def is the declaration of a function
  • My func is the name of the function
  • message is the parameter of the function
  • print is the main part of the function
  • At the end of the function, you can return the call result (return or yield) or not

Defined before, called after

def my_sum(a, b):
    return a + b
​
result = my_sum(3, 5)
print(result)
​
# output
8

You can set default values for the parameters of a function

def func(param = 0):
    ...

If param is not passed in, the parameter defaults to 0. If param is passed in, the default value is overwritten.

2. Polymorphism

The parameter passed in can accept any data type

For example, list

print(my_sum([1, 2], [3, 4]))
​
Export output
[1, 2, 3, 4]
For example, string

print(my_sum('hello ', 'world'))
​
Export output
hello world

Of course, if the parameter data types are different, the two cannot be added

print(my_sum([1, 2], 'hello'))
TypeError: can only concatenate list (not "str") to list

The same function can be applied to integer, list, string and so on is called polymorphism. It's not a pervert.

3. Function nesting

Function nesting means that there are functions in a function, which is called nested function.

def f1():
    print('hello')
    def f2():
        print('world')
    f2()
f1()
​
# output
hello
world

The nesting of functions ensures the calling of internal functions, which can only be called by external functions and will not work in the whole local area.

Reasonable use of function nesting, improve the speed of operation.

For example, calculate the factorial of 5.

def factorial(input):
    
    if not isinstance(input, int):
        raise Exception('input must be an integer.')
    if input < 0:
        raise Exception('input must be greater or equal to 0' )
  
    def inner_factorial(input):
        if input <= 1:
            return 1
        return input * inner_factorial(input-1)
    return inner_factorial(input)
​
​
print(factorial(5))
​
120

4. Function variable scope

If a variable is defined within an izai function, it is called a local variable, which is only valid within the function. When the function is executed, the local variable will be recycled. Global variables are written outside functions.

MIN_VALUE = 1
MAX_VALUE = 10
def validation_check(value):
    if value < MIN_VALUE or value > MAX_VALUE:
        raise Exception('validation check fails')

Min and max values here are global variables, but we can't change the values of global variables at will within the function

MIN_VALUE = 1
MAX_VALUE = 10
def validation_check(value):
    ...
    MIN_VALUE += 1
    ...
validation_check(5)
UnboundLocalError: local variable 'MIN_VALUE' referenced before assignment

If you want to change, you have to add the global statement

MIN_VALUE = 1
MAX_VALUE = 10
def validation_check(value):
    global MIN_VALUE
    ...
    MIN_VALUE += 1
    ...
validation_check(5)

Global tells the python parser that the function's internal variable min'u value is the defined global variable, and the input here is 2, which modifies the value of the global variable

MIN_VALUE = 1
MAX_VALUE = 10
def validation_check(value):
    MIN_VALUE = 3
    ...
MIN_VALUE = 1
MAX_VALUE = 10
def validation_check():
    MIN_VALUE = 3
    print(MIN_VALUE)
validation_check()
print(MIN_VALUE)
​
​
# 3
# 1

For nested functions, internal functions cannot modify the variables defined by external functions. They can be accessed. If you want to modify them, you need to add non local

def outer():
    x = "local"
    def inner():
        nonlocal x # The nonlocal keyword indicates that the X here is the variable x defined by the outer function
        x = 'nonlocal'
        print("inner:", x)
    inner()
    print("outer:", x)
outer()
# output
inner: nonlocal
outer: nonlocal

No coverage without adding

def outer():
    x = "local"
    def inner():
        x = 'nonlocal' # Here, x is the local variable of the inner function
        print("inner:", x)
    inner()
    print("outer:", x)
outer()
# output
inner: nonlocal
outer: local

5, closure

A closure is a function called in a function. It is usually executed by return, which gives the function name of the internal call.

Calculate the n power of a number

def nth_power(exponent):
    def exponent_of(base):
        return base ** exponent
    return exponent_of # The return value is the exponent of function
​
square = nth_power(2) # Calculate the square of a number
cube = nth_power(3) # Calculate the cube of a number
square
# output
<function __main__.nth_power.<locals>.exponent(base)>
​
cube
# output
<function __main__.nth_power.<locals>.exponent(base)>
​
print(square(2))  # Calculate the square of 2
print(cube(2)) # Calculate the cube of 2
# output
4 # 2^2
8 # 2^3

Source network, only for learning, if there is infringement, contact delete.

I have collected high-quality technical articles and experience summary in my official account [Python circles].

Don't panic. I have a set of learning materials, including 40 + E-books, 600 + teaching videos, involving Python foundation, reptile, framework, data analysis, machine learning, etc. I'm not afraid you won't learn! There are also learning exchange groups, learning and progress together~

file

Posted by davidsakh on Thu, 09 Apr 2020 03:07:18 -0700