python-Fundamentals of Functions

Posted by xiledweb on Sat, 24 Aug 2019 08:49:58 +0200

Catalog

1 Return value

def func(arg):
    # ....
    return 9 # The return value is 9 by default: return None

val = func('adsfadsf')
# 1. Let the user input a string and calculate how many A characters are in the string. How many are written in the document a.txt as many as "Li Shaoqi".

def get_char_count(data):
    sum_counter = 0
    for i in data:
        if i == 'A':
            sum_counter += 1
            
    return sum_counter

def write_file(line):
    if len(line) == 0:
        return False  # In the process of function execution, once the return is encountered, the execution of the function is stopped.
    with open('a.txt',mode='w',encoding='utf-8') as f:
        f.write(line)
    return True 

content = input('Please enter:')
counter = get_char_count(content)
write_data = "Li Shaoqi" * counter 
status = write_file(write_data)
if status:
    print('Write successfully')
else:
    print('Write failure')

When the function does not return a value, it returns None by default.

The function terminates when it encounters return during internal execution.

def func1():
    return "complete" # The function returns every time it executes here; so the following code never executes.
    for i in range(10):
        print(i)
func1()               


def func2():
    for i in range(10):
        print(i)
        return "complete"
    print(666)
func2()        # Print only 0

Return can return any value

Special case: When return returns multiple values, it returns tuples, the same as when the return value is tuples

def func():
    return (1,2,3)

v = func()
print(v)

# Special: Return tuples
def func():
    return 5,8,"alex"

v = func()
print(v)

Role of return: a. Return value b. Execution of termination function

Exercises

# 1. Write a function to calculate how many numbers there are in a list. Print: There are% s numbers in the list.
#    Tip: type('x') == int to determine whether it is a number.

# Mode 1:
def get_list_counter1(data_list):
    count = 0
    for item in data_list:
        if type(item) == int:
            count += 1
    msg = "The list contains%s Numbers" %(count,)
    print(msg)
    
get_list_counter1([1,22,3,'alex',8])

# Mode 2:
def get_list_counter2(data_list):
    count = 0
    for item in data_list:
        if type(item) == int:
            count += 1
    return count
    
v = get_list_counter1([1,22,3,'alex',8])
msg = "The list contains%s Numbers" %(v,)
print(msg)
# 2. Write a function to construct another list by calculating the data of the even index position in one list and returning it.
# Mode 1:
def get_data_list1(arg):
    v = arg[::2]
    return v

data = get_data_list1([11,22,33,44,55,66])

# Mode 2:
def get_data_list2(arg):
    v = []
    for i in range(0,len(arg)):
        if i % 2 == 0:
            v.append(arg[i])
    return v

data = get_data_list2([11,22,33,44,55,66])
# 3. Read the file, construct the content of the file into the data in the specified format, and return it.
"""
a.log file
    alex|123|18
    eric|uiuf|19
    ...
//Target structure:
a.  ["alex|123|18","eric|uiuf|19"] And return.
b. [['alex','123','18'],['eric','uiuf','19']]
c. [
    {'name':'alex','pwd':'123','age':'18'},
    {'name':'eric','pwd':'uiuf','age':'19'},
]
"""

with open('a.log.txt',mode = 'r',encoding = 'utf-8') as f:
    data = f.read()
    print(data)
    def get_file(a):
        date1 = []
        for i in a.split('\n'):
            date1.append(i)
        return date1
    v1 = get_file(data)
    print(v1)

    def get_file1(b):
        date2 = []
        d = []
        for i1 in b.split('\n'):
            i1 = i1.split('|')
            d.append(i1)
            date2 += d
        return date2
    v2 = get_file1(data)
    print(v2)

    def get_file2(c):
        date3 = []
        e = {}
        for i2 in c.split('\n'):
            i2 = i2.split('|')
            e['name'] = i2[0]
            e['pwd'] = i2[1]
            e['age'] = i2[2]
            date3.append(e)
        return date3
    v3 = get_file2(data)
    print(v3)
  1. Is there a return value for the method in the data type?
  • No return value

    v = [1,2,3,4]
    v.append(55)   # Do not write return when there is no return value

    list : append / insert / remove / clear / extend / reverse

    dict : update

    set : add / discard / update

  • Only return value

    v = 'ddff2dd554cvc'
    result = '-'.join(v)
    return result
    
    v = {'k1':12,'k2':'ased'}
    result = v.get('k2')
    result = v.keys()

    str : upper / lower / replace / isdecimal / strip / split / startswith / endswith / encode / format / join

    list : find / index

    dict : keys / values / items / get

    set : intersection / union / difference / symmitric_difference

  • Return Value + Modify Data

    pop

    v = [11,22,33,44]
    result = v.pop(22)
    
  • Commonly used to be remembered

    Index and slice all have return values

    Str: split return list

      strip returns a string
    
      replace returns a string
    
      join returns a string

    List: append none

       insert without
    
       remove none
    
       pop returns the data to be deleted
    
       find returns the location of the index
    
       Index returns the location of the index

    Dict: keys get all keys

         Values gets all the values
    
         items gets all key-value pairs
    
         The get index exists: return value, nonexistence: return None

2 Scope

In the python file:

  • py file: global scope

  • Function: Local scope

    a = 1
    def s1():
        x1 = 666
        print(x1)
        print(a)
        print(b)
    
    b = 2
    print(a)
    s1()
    a = 88888
    def s2():
        print(a,b)
        s1()
    
    s2()
    
  • Data in each scope can only be invoked by the scope itself. If the data invoked in the scope is not available, the global scope can be invoked.

    Global scope can only call Global

    Functions in global scope can call each other (calling existing ones), but they cannot call scopes directly in scope.

Summary:

  • 1. A function is a scope.

  • 2. The rule of finding data in scope: first find data in one's own scope, and then go to "parent"--> "parent"--> until the whole situation, the whole situation will not be reported. (Scope nesting)

    Note: What is the value in the parent scope?

    x = 10
    def func():
        x = 9
        print(x)
    
    func()

    Small exercises

    # Example 1
    x = 10
    def func():
        x = 9
        print(x)
        def x1():
            x = 999
            print(x)        
    func()
    
    # Example 2
    x = 10
    def func():
        x = 9
        print(x)
        def x1():
            x = 999
            print(x)
        x1()   
    func()
    
    # Example 3
    x = 10
    def func():
        x = 9
        print(x)
        def x1():
            x = 999
            print(x)
        print(x)
        x1()
    func()
    
    # Example 4
    x = 10
    def func():
        x = 8
        print(x)
        def x1():
            x = 999
            print(x)
        x1()
        print(x)
    func()
    
    # Example 5
    x = 10
    def func():
        x = 8
        print(x)
        def x1():
            print(x)
        x1()
        print(x)
    func()
    
    # Example 6
    x = 10
    def func():
        x = 8
        print(x)
        def x1():
            print(x)
        x = 9
        x1()
        x = 10
        print(x)
    func()
    
    # Example 7
    x = 10
    def func():
        x = 8
        print(x)
        def x1():
            print(x)    
        x1()
        x = 9
        x1()
        x = 10
        print(x)
    
    func()
  • 3. Values in the parent can only be found in the child scope, and cannot be reassigned to variables in the parent by default.

    • No assignment, only internal modification of variable types

      # #####################
      name = 'oldboy'
      def func():
          name = 'alex' # Create another such value in your own scope.
          print(name)
      func()
      print(name)
      
      
      # #####################
      name = [1,2,43]
      def func():
          name.append(999)
          print(name)
      func()
      print(name)
    • If you have to assign global variables, you need to add global (mandatory assignment)

      #Example 1
      name = "Old boy“
      def func():
          global name
          name = 'alex'
      func()
      print name
      
      # Example 2
      name = ["Old boy",'alex']
      def func():
          global name
          name = 'I'
      func()
      print(name)
      
      # Example 3
      name = "Old boy"
      def func():
          name = 'alex'
          def inner():
              global name
              name = 999
          inner()
          print(name)
      func()
      print(name)
      
    • To assign a parent variable to a nonlocal value, first find the parent variable and then assign it (mandatory assignment)

      name = "Old boy"
      def func():
          name = 'alex'
          def inner():
              nonlocal name # Find the name of the previous level
              name = 999
          inner()
          print(name)
      func()
      print(name)

Supplement: Global variables must all be capitalized

USER_LIST = [11,22,3]

def func():
    name = 'asdf'
    USER_LIST.append(12)
    USER_LIST.append(name)

func()
print(USER_LIST)

3 Functions

    1. Function names can be used as variables

      def func():
          print(123)
      
      v1 = func  # Address of func representative function
      
      func()
      v1()   # v1 and func have the same function address and the same function to execute the call
      def func():
          print(123)
      
      func_list = [func, func, func]
      # func_list[0]()  a
      # func_list[1]()  b
      # func_list[2]()  c
      for item in func_list:   # Simplified form of a/b/c
          v = item()
          print(v)
      def func():
          print(123)
      
      def bar():
          print(666)
      
      info = {'k1': func, 'k2': bar}
      
      info['k1']()           # Functions can also be used as dictionary values (or keys, but not meaningful)
      info['k2']()

      Note: Functions are immutable. They can be elements of a collection or keys of a dictionary (but keying doesn't make much sense).

             Multiple duplicate functions can be placed in a collection, but only executed once. (Because of the characteristics of collections: non-repeatable)

      Confuse you

      def func():
          return 123
      
      func_list1 = [func,func,func]
      func_list2 = [func(),func(),func()]
      
      print(func_list1)     # The function address of func is printed.
      print(func_list2)     # Printed is the value returned by func after execution
      
      info = {
          'k1':func,     # Address of function
          'k2':func(),   # Value returned after function execution
      }
      
      print(info)
    2. Functions can also be passed as parameters

      def func(arg):
          print(arg)
      
      func(1)
      func([1,2,3,4])
      
      def show():
          return 999
      func(show)      # The function func is executed with the parameter show and show has no +(), which means that show does not execute but only represents the address of the function.
      def func(arg):
          v1 = arg()
          print(v1)
      
      def show():
          print(666)
      
      func(show)
      def func(arg):
          v1 = arg()
          print(v1)
      
      def show():
          print(666)
      
      result = func(show)
      print(result)

      Calling multiple functions

      def func():
          print('Cost query')
      
      def bar():
          print('Voice communication')
      
      def base():
          print('xxx')
      
      def show():
          print('xxx')
      
      def test():
          print('xxx')
      
      info = {
          'f1': func,
          'f2': bar,
          'f3':base,
          'f4':show,
          'f5':test
      }
      choice = input('Please select the function to choose:')
      function_name = info.get(choice)
      if function_name:
          function_name()
      else:
          print('Input error')

Summary: Functions are treated as variables: parameter values are passed / nested in dictionaries and lists as elements

4 Functions of Intermediate and Advanced Level

4.1 function can be used as return value

# Example 1
def func():
    print(123)

def bar():
    return func

v = bar()
v()

# Example 2
name = 'oldboy'
def func():
    print(name)
    
def bar():
    return func

v = bar()
v()

# Example 3
def bar():
    def inner():
        print(123)
    return inner
v = bar()
v()

# Example 4
name = 'oldboy'
def bar():
    name = 'alex'
    def inner():
        print(name)
    return inner
v = bar()
v()

# Example 5
name = 'oldboy'
def bar(name):
    def inner():
        print(name)
    return inner
v1 = bar('alex') # { name=alex, inner }  # Closure, which creates an area for a function (internal variables for its own use, stored code) to provide data for its subsequent execution.
v2 = bar('eric') # { name=eric, inner }
v1()
v2()

# Example 6
name = 'alex'
def base():
    print(name)

def func():
    name = 'eric'
    base()

func() # {name=eric, }
    
# Example 7
name = 'alex'
def func():
    name = 'eric'
    def base():
        print(name)
    base()
func()

# Example 8
name = 'alex'
def func():
    name = 'eric'
    def base():
        print(name)
    return base 
base = func()
base()

Note: When and who created the function?

      Who created the function, and where to start looking for the execution function
# Exercise 1
info = []

def func():
    print(item)
    
for item in range(10):
    info.append(func)

info[0]()

# Exercise 2
info = []

def func(i):
    def inner():
        print(i)
    return inner

for item in range(10):
    info.append(func(item))

info[0]()
info[1]()
info[4]()

4.2 Closure

def func(name):
    def inner():
        print(name)
    return inner 

v1 = func('alex')
v1()
v2 = func('eric')
v2()

Return value - Memory to analyze function execution. (Closure is one of memory)

# Not closures
def func(name)
    def inner():
        return 123
    return inner
# It is the closure that needs to satisfy two conditions: 1. the encapsulation value 2. the inner function needs to be used
def func(name)
    def inner():
        print(name)
        return 123
    return inner

4.3 Higher Order Functions

  • Transfer functions as parameters

  • Consider a function as a return value

    Note: Assignment of functions

4.4 Summary

  • 1. Analysis of function execution process (who created the function in the end?)
  • 2. Closure concept: Create a region for a function and maintain its own data for easy invocation. (Application Scenario: Decorator / SQLAlchemy Source)

Topics: Python encoding