- Function-function II

01. - Function - Return Value

(1). Find the sum of any number

You can specify the return value of a function by returning

def fn(*nums):

    # Define a variable to hold the result
    result = 0

    # Traversing through tuples and accumulating elements in tuples
    for n in nums:

        result += n
    print(result)    # 10
fn(1,2,3,4)

(2). Return values can be used directly, or they can be cleaned up by a variable.

return can be followed by any object, or even a function.

def fn():
    # return 100           #   100
    # return [1,2,3]       #  [1, 2, 3]
    # return 1 + 1         #  2
    # return False         #  False
    def fn2():
        print('python')
    return fn2
r = fn()
r()        #  python
print(r)   #  <function fn.<locals>.fn2 at 0x0000021240783EA0>

(3) If only one return is written or no return is written, it is equivalent to return None.

def fn2():
    a = 10   # None
    return   # None
r = fn2()
print(r)

(4). In a function, the code after return will not execute. Once the return is executed, the function automatically ends.

def fn3():
    print('hello')
    return
    print('abc')
r = fn3()
print(r)
>>>
hello
None

(5). Use of break, continue and return

def fn4():
    for i in range(5):
        if i == 3:
            # break   # 0  1  2  End of cycle # Used to exit the current loop
            # continue  # 0 1 2 4 End of cycle # Used for recirculation
            return     # 0 1 2     #  Used to terminate functions
        print(i)
    print('End of cycle')
fn4()

(6). Find the sum of any number

You can specify the return value of a function by returning

def fn(*nums):

    //Define a variable to hold the result
    result = 0

    //Traversing through tuples and accumulating elements in tuples
    for n in nums:

        result += n
   # print(result) 
   return result
r = fn(1,2,3)
print(r)                     #  6
print(r + 6)          	   #  12

(7). The difference between fn5 and fn(5):

def fn5():
    return 10

print(fn5)    # <function fn5 at 0x0000016BA2273EA0> fn5 is a function object, actually printing a function object
print(fn5())    # 10   # fn5() is calling a function, actually printing the return value of the fn5() function.

02. - Function - Document String

(1). help() can query the use of Python functions

Syntax help (function object)
help(print) # executes directly without printing

def fn(a:int,b:str,c:bool) -> int:         #  (-> int is to tell others that the return value is an int type)
    '''

    //Parameters of functions
    :param a:  Effect ....
    :param b:  Effect....
    :param c:  Effect
    :return:  int
    '''
    return 10

help(fn)
>>>
Help on function fn in module __main__:

fn(a:int, b:str, c:bool) -> int
    //Parameters of functions
    :param a:  Effect ....
    :param b:  Effect....
    :param c:  Effect
    :return:  int

03. - Function - Function Scope

1. Scope refers to the area in which the variable takes effect.

2. There are two scopes in Python

(1) Global scope: global scope and functional scope

Global scopes are created at the time of program execution and destroyed at the end of the program
Areas other than all functions are global scopes
Variables redefined in global scope belong to global variables, which can be accessed anywhere in the program.

(2). Functional scope

Function scopes are created at the time of a function call and destroyed at the end of the call
The scope of a new function is generated without a single call to the function
Variables defined in the scope of a function are local variables, which can only be accessed inside the function.

b = 20
def fn():

    a = 10   # a is defined inside the function, so its scope is inside the function and there is no access outside the function.

    print('Function interior:','a =',a)
    print('Function interior:','b =',b)

fn()

# print('outside the function:','a = a', a)
print('External function:','b =',b)
>>>
//Function interior: a = 10
//Function interior: b = 20
//Function exterior: b = 20

def fn2():
    a = 30
    def fn3():
        print('fn3 in:','a =',a)        #  fn3: a = 30
    fn3()
fn2()

3. global a

If you want to modify global variables within a function, you need to use the global keyword to declare variables

global a # declares that the use of a within a function is a global variable, and then to modify a is to modify the global variable.

(1) Before the global a declaration:

a = 20
def fn2():

    a = 10
    print('Function interior','a =',a)

fn2()
print('External function:','a =',a)
>>>
//Function interior a = 10
//Function exterior: a = 20

(2) After the global a declaration:

a = 20
def fn2():
	# If you want to modify global variables within a function, you need to use the global keyword to declare variables
    global a  # Declare that the use of a within a function is a global variable, and then modify a is to modify the global variable.
    a = 10
    print('Function interior','a =',a)

fn2()
print('External function:','a =',a)
>>>
//Function interior a = 10
//Function exterior: a = 10

04. - Function - Namespace

(1) Namespace is actually a dictionary, a dictionary dedicated to storing variables.

locals() is used to get the namespace of the current scope

If the locals() function is called in the global scope, the global scope namespace is obtained, and if locals() is called in the function scope, the function namespace is obtained.

The return is a dictionary (Dict)

1. Namespaces outside functions:

a = 30
b = 40
s = locals()  # Get the current namespace
print(s)
print(a)
print(s['a'])
s['c'] = 200   # Add a variable c to the namespace
print(s)
>>>
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000020D5E4AC128>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/Software Installation Package/pyCharm Document items/Demon1.py', '__cached__': None, 'a': 30, 'b': 40, 's': {...}}
30
30
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000020D5E4AC128>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/Software Installation Package/pyCharm Document items/Demon1.py', '__cached__': None, 'a': 30, 'b': 40, 's': {...}, 'c': 200}

2. Namespaces within functions:

def fn4():
    a = 10        # Define a variable and assign 10 to a
    s = locals()  # Calling locals() inside a function obtains the namespace of the function
    s['b'] = 20   # Namespaces of functions can be manipulated by s, but this is not recommended (my understanding: you can also define a variable B by using namespaces)
    print(s['b']) # 20
    print(s)      # {'a': 10, 'b': 20}

fn4()

05. - Function - Recursion

1. Try to find the factorial of 10 (10!)

1! = 1
2! = 12 = 2
3! = 123 = 6
4! = 1234 = 24

print(1*2*3*4*5*6*7*8*9*10)          #  3628800

n = 10
for i in range(1,10):
   n *= i
print(n)                                       #  3628800

2. Create a function to compute the factorial of any number.

def fn(n):

    # Create a variable to receive the result
    result = n

    for i in range(1,n):
        result *= i

    return result
print(fn(10))          #  3628800

3. Recursive function

Recursive simple understanding is to call oneself
Recursive functions call themselves in functions.

This is a functional grammar format for infinite recursive functions:
def fn2():

    fn2()
fn2()

4. Recursion is a way to solve problems

Two conditions of recursive function:

(1) Baseline conditions

The problem can be decomposed into the smallest problem. When the baseline condition is satisfied, the recursive complement is executed.

(2) Recursive conditions

Conditions for continued decomposition of problems
4! = 1234 = 24 # 4 * 3!
3! = 123 = 6 # 3 * 2!
2! = 12 = 2 # 2 * 1!
1! = 1

def fn2(n):

    # Baseline conditions
    if n == 1:

    # The factorial of 1 is itself
        return 1

    # Recursive condition
    return n * fn2(n-1)

print(fn2(10))
>>>
3628800

06. - Function - Recursive Exercise

Exercise 1: Create a function to do any power operation for any number

24 = 222*2 = 16
23 = 222 = 8
22 = 2*2 = 4
21 = 2

def fn4(n,i):

    # A function is defined, which has two parameters, n is the base of power operation and i is the exponent of power operation.
    # Baseline conditional power 1
    if i == 1:

        # When i = 1, return to itself
        return n

    # Recursive condition 2*2*2*2=162**4
    return n * fn4(n,i - 1)   # Return n** I can also

print(fn4(9,9))

Exercise 2: Create a function to check whether any string is a palindrome string, and if it returns True, it does not return False.

Palindrome strings, which read from the back to the front, are the same as those read from the front to the back: abcba
Judging whether abcdefgfedcba is a palindrome string

Check that the first character and the last one are consistent, if not, they are not palindrome strings.
If consistent, see if the rest is a palindrome string
Check whether bcdefgfedcb is a palindrome string
Check if cdefgfedc is a palindrome string
Check whether defgfed is a palindrome string
Check if efgfe is a palindrome string
Check if fgf is a palindrome string
Check if g is a palindrome string

def fn5(s):
    # This function checks whether any string is a palindrome string or not.
    # The parameter s is the string we want to check

    # Baseline conditions
    if len(s) < 2:

        # If the length of the string is less than 2, the string must be a palindrome string
        return True

    elif s[0] != s[-1]:

        # If the first character is not equal to the last character, it is not a palindrome string.
        return False

    # Recursive condition
    return fn5(s[1:-1])

print(fn5('bcdefgfedcb'))      #  True
print(fn5('b1551b'))             #  True
print(fn5('1'))                       #  True
print(fn5(''))                         #   True  
 //This is an empty string. It's also a palindrome string.

07. - Functions - Advanced Functions

Characteristic:

1. Receive one or more functions as parameters
2. Return a function as a return value

The above two points satisfy any one of the characteristics of high-level functions.

(1) The original scheme

# Defining a function can save all even numbers in a specified list and return them to a new list
l = [1,2,3,4,5,6,7,8,9,10]

# Define a function

def fn(lst):

    # Create a new list
    new_list = []

    for n in lst:

        # Judging the parity of n
        if n % 2 == 0:
            new_list.append(n)

    # Returns a new list
    return new_list

print(fn(l))   #   [2, 4, 6, 8, 10]

(2) The improved scheme 1:

Defining a function allows you to specify all even numbers in a given list,Save to a new list and return
l = [1,2,3,4,5,6,7,8,9,10]

# Define a function


def fn(lst):    # Pass a variable n

    # Define a function to detect an arbitrary even number
    def fn2(i):

        if i % 2 == 0:
            return True

    # Create a new list
    new_list = []

    for n in lst:

        # Judging the parity of n
        if not fn2(n):
            new_list.append(n)

    # Returns a new list
    return new_list

print(fn(l))   #   [1, 3, 5, 7, 9]

(3) The improved scheme 2:

# The improved scheme 2:
# Defining a function can save all even numbers in a specified list and return them to a new list
l = [1,2,3,4,5,6,7,8,9,10]

# Define a function
def fn(lst):    # Pass a variable n

    # Define a function to detect an arbitrary even number
    def fn2(i):

        if i % 2 == 0:
            return True

    # Define a function to detect whether the specified number is greater than 5
    def fn3(i):

        if i > 5:
            return True
        return False


    # Create a new list
    new_list = []

    for n in lst:

        # Judging the parity of n
        # if not fn2(n):       # [2, 4, 6, 8, 10]
        if fn3(n):             # [6, 7, 8, 9, 10]
            new_list.append(n)

    # Returns a new list
    return new_list

print(fn(l))   #   [1, 3, 5, 7, 9]

(4) The improved scheme 3: When we use a function as a parameter, we actually transfer the specified code (a program or a function) into the objective function.

# After improvement, Fang 3:
# Defining a function can save all even numbers in a specified list and return them to a new list
l = [1,2,3,4,5,6,7,8,9,10]

# Define a function to detect an arbitrary even number
def fn2(i):
    if i % 2 == 0:
        return True

# Define a function to detect whether the specified number is greater than 5
def fn3(i):
    if i > 5:
        return True
    return False

# Create a new list
new_list = []

# Define a function
def fn4(i):

    if i % 3 == 0:
        return True
    return False

def fn(func,lst):    # Pass a variable n

    for n in lst:

        # Judging the parity of n
        # if not fn2(n):       # [2, 4, 6, 8, 10]
        # if fn3(n):           # [6, 7, 8, 9, 10]
        if func(n):            # [2, 4, 6, 8, 10]
            new_list.append(n)

    # Returns a new list
    return new_list

print(fn(fn2,l))   #  [2, 4, 6, 8, 10]      # fn2 is passing objects here, not calling functions.
print(fn(fn3,l))   #  [6, 7, 8, 9, 10]
print(fn(fn4,l))   #  [3, 6, 9]
# When we use a function as a parameter, we actually pass the specified code (a program or a function) into the target function.

Keywords: Python Pycharm REST less

Added by Snorkel on Tue, 30 Jul 2019 12:24:17 +0300