python-Fundamentals of Functions

Keywords: Python Programming

Catalog

1 Process-oriented Programming and Functional Programming

Up to now, the programming we have come into contact with and written is process-oriented programming [poor readability/poor reusability]

# PROCESS-ORIENTED PROGRAMMING
user_input = input('Please enter roles:')

if user_input == 'Administrators':
    import smtplib
    from email.mime.text import MIMEText
    from email.utils import formataddr

    msg = MIMEText('Administrator, I want to be No. 1 man. You can do whatever you want.', 'plain', 'utf-8')
    msg['From'] = formataddr(["Li Shaoqi", '15776556369@163.com'])
    msg['To'] = formataddr(["Administrators", '344522251@qq.com'])
    msg['Subject'] = "Love Director"

    server = smtplib.SMTP("smtp.163.com", 25)
    server.login("15776556369@163.com", "qq1105400511")
    server.sendmail('15776556369@163.com', ['Administrators', ], msg.as_string())
    server.quit()
elif user_input == 'Salesman':
    import smtplib
    from email.mime.text import MIMEText
    from email.utils import formataddr

    msg = MIMEText('Salesman, I want to be No. 1 man. You can do whatever you want.', 'plain', 'utf-8')
    msg['From'] = formataddr(["Li Shaoqi", '15776556369@163.com'])
    msg['To'] = formataddr(["Salesman", 'Salesman'])
    msg['Subject'] = "Love Director"

    server = smtplib.SMTP("smtp.163.com", 25)
    server.login("15776556369@163.com", "qq1105400511")
    server.sendmail('15776556369@163.com', ['Salesman', ], msg.as_string())
    server.quit()
elif user_input == 'Boss':
    import smtplib
    from email.mime.text import MIMEText
    from email.utils import formataddr

    msg = MIMEText('Boss, I want to be No. 1 man. You can do whatever you want.', 'plain', 'utf-8')
    msg['From'] = formataddr(["Li Shaoqi", '15776556369@163.com'])
    msg['To'] = formataddr(["Boss", 'Boss mailbox'])
    msg['Subject'] = "Love Director"

    server = smtplib.SMTP("smtp.163.com", 25)
    server.login("15776556369@163.com", "qq1105400511")
    server.sendmail('15776556369@163.com', ['Boss mailbox', ], msg.as_string())
    server.quit()
# Functional Programming
def send_email():
    import smtplib
    from email.mime.text import MIMEText
    from email.utils import formataddr

    msg = MIMEText('Boss, I want to be No. 1 man. You can do whatever you want.', 'plain', 'utf-8')
    msg['From'] = formataddr(["Li Shaoqi", '15776556369@163.com'])
    msg['To'] = formataddr(["Boss", 'Boss mailbox'])
    msg['Subject'] = "Love Director"

    server = smtplib.SMTP("smtp.163.com", 25)
    server.login("15776556369@163.com", "qq1105400511")
    server.sendmail('15776556369@163.com', ['Boss mailbox', ], msg.as_string())
    server.quit()


user_input = input('Please enter roles:')

if user_input == 'Administrators':
    send_email()
elif user_input == 'Salesman':
    send_email()
elif user_input == 'Boss':
    send_email()

For functional programming:

  • Essence: Get N lines of code somewhere else and give him a name, then you can find the code by name and execute it.
  • Scene:
    • Code repetition
    • Code in particular more than one screen, you can choose to split the code through functions

The Basic Structure of 2 Functions

# Definition of function
 def function name (): # function name naming specifications, recommendations and variables
    # Function content (indentation)
    pass

# Execution of functions
 Function name ()
def get_list_first_data():
    v = [11,22,33,44]
    print(v[0])

get_list_first_data()

# Note: If the function is not called, the internal code will never be executed.
# Suppose: The administrator / salesman / boss uses the same email address.
def send_email():
    print('Successful email delivery, assuming that there are 10 codes')


user_input = input('Please enter roles:')

if user_input == 'Administrators':
    send_email()
elif user_input == 'Salesman':
    send_email()
elif user_input == 'Boss':
    send_email()

Summary:

# Situation 1
def f1():
    pass 
f1()

# Situation 2
def f2(a1):
    pass 
f2(123)

# Situation 3
def f3():
    return 1 
v1 = f3()

# Situation 4
def f4(a1,a2):
    # ... 
    return 999
v2 = f4(1,7)
def show(name,age):
    """
    What does a function do? Functions must be specified
    :param name: 
    :param age: 
    :return: 
    """
    return None

Is the data inside a function confusing: (the execution of functions and functions does not affect each other)

  • 1. Function Execution Completed
  • 2. Internal elements are not used by others - > Number of memory executed by the destroy function

Parameters of function 3

def get_list_first_data(aaa): # aaa is called formal parameter.
    v = [11,22,33,44]
    print(v[aaa])
    
get_list_first_data(1) # When 2/2/1 calls a function, it passes the actual parameter (argument).
get_list_first_data(2)
get_list_first_data(3)
get_list_first_data(0)

Pass parameters strictly in sequence: position mode

Actual parameters can be of any type

# Suppose: The administrator / salesman / boss uses the same email address.
"""
def send_email(to):
    import smtplib
    from email.mime.text import MIMEText
    from email.utils import formataddr

    msg = MIMEText('Director, I want to be No. 1 man. You can do whatever you want.', 'plain', 'utf-8')
    msg['From'] = formataddr(["Li Shaoqi", '15776556369@163.com'])
    msg['To'] = formataddr(["director", to])
    msg['Subject'] = "Love Director"

    server = smtplib.SMTP("smtp.163.com", 25)
    server.login("15776556369@163.com", "qq1105400511")
    server.sendmail('15776556369@163.com', [to, ], msg.as_string())
    server.quit()
"""
def send_email(to):
    template = "To give%s Send mail" %(to,)
    print(template)
 

user_input = input('Please enter roles:')

if user_input == 'Administrators':
    send_email('xxxx@qq.com')
elif user_input == 'Salesman':
    send_email('xxxxo@qq.com')
elif user_input == 'Boss':
    send_email('xoxox@qq.com')

Exercises

# 1. Write a function that calculates the sum of all elements in the list info = 11, 22, 33, 44, 55.

def get_sum():
    info = [11,22,33,44,55]
    data = 0
    for item in info:
        data += item
    print(data)

get_sum()

# 2. Write a function that calculates the sum of all elements in the list.

def get_list_sum(a1):
    data = 0
    for item in a1:
        data += item
    print(data)
    
get_list_sum([11,22,33])
get_list_sum([99,77,66])
v1 = [8712,123,123]
get_list_sum(v1)

# 3. Write a function that splits the two lists together.
def join_list(a1,a2):
    result = []
    result.extend(a1)
    result.extend(a2)
    print(result)
    
join_list([11,22,33],[55,66,77]

# 4. Calculate the length of a list
def my_len(arg):
    count = 0
    for item in arg:
          count += 1
    print(count)

v = [11,22,33]
my_len(v)
len(v)

# 5. Examples of mailing
          
def send_email(role,to):
    template = "To give%s%s Send mail" %(role,to,)
    print(template)
 

user_input = input('Please enter roles:')

if user_input == 'Administrators':
    send_email('Administrators','xxxx@qq.com')
elif user_input == 'Salesman':
    send_email('Salesman','xxxxo@qq.com')
elif user_input == 'Boss':
    send_email('Boss','xoxox@qq.com')

3.1 shape parameter

3.1.1 Basic parameter knowledge
  • The parameters can be any number.

  • It can be of any type.

    def func(a1,a2,a3,a4):
      print(a1,a2,a3,a4)
    
    func(2,'name',[1,2,3],False)
3.1.2 Default parameters
def func(a1,a2,a3=9,a4=10):   # The default parameters a3=9,a4=10
    print(a1,a2,a3,a4)

func(11,22)       # If the values of A3 and A4 are not passed, then A3 and A4 are equal to the default parameters.
func(11,22,10)
func(11,22,10,100)
func(11,22,10,a4=100)
func(11,22,a3=10,a4=100)
func(11,a2=22,a3=10,a4=100)
func(a1=11,a2=22,a3=10,a4=100)
3.13 Universal Parameters (for Dispersion)
  • *args

    It can accept any number of position parameters and convert them into tuples.

    1. Call function without*

    def func(*args):
      print(*args)
    
    func(1,2)   ==> (1,2)
    func(1,2,[12,3,4])   ==> (1,2,[12,3,4])
    func((11,22,33))   ==> ((11,22,33))  # The parameter is a tuple, and the print effect is tuple set tuple.

    2. The calling function has*

    def func(*args):
      print(args)
    
    func(*(11,22,33))   ==>(11,22,33)    # * It is used to break up tuples, with each element in the tuple as a parameter.
    func(*[11,22,33])   ==>(11,22,33)    # * It can be used to hash lists / tuples / dictionaries / collections, just the inner elements of loops

    3. Reference can only be transmitted by location.

    def func(*args):
        print(args)
    
    func(1)
    func(1,2)   # args=(1, 2)
    func((11,22,33,44,55))    # args=((11,22,33,44,55),)
    func(*(11,22,33,44,55))   # args=(11,22,33,44,55)
  • **kwargs

    Can accept any number of keyword parameters, and see the parameters into a dictionary

    1. Call function without*

    def func(**kwargs):
      print(***kwargs)
    
    func(k=1)    **kwargs = {'k':1}
    func(k1=1,k2=3)   **kwargs = {'k1':1,'k2':3}

    2. The calling function has*

    def func(**kwargs):
      print(kwargs)
    
    func(**{'k1':1,'k2':4,'k3':9})   **kwargs = {'k1':1,'k2':4,'k3':9}

    3. Reference can only be transmitted by keywords

  • * Comprehensive Use of args/**kwargs: Invincible + Invincible=> Really Invincible

    def func(*args,**kwargs):
        print(args,kwargs)
    
    func(1,2,3,4,5,k1=2,k5=9,k19=999)     *arg = (1,2,3,4,5) **kwargs = {'k1':2,'k5':9,'k19':999}
    func(*[1,2,3],k1=2,k5=9,k19=999)      *arg = (1,2,3) **kwargs = {'k1':2,'k5':9,'k19':999}
    func(*[1,2,3],**{'k1':1,'k2':3})      *arg = (1,2,3) **kwargs = {'k1':1,'k2':3}
    func(111,222,*[1,2,3],k11='alex',**{'k1':1,'k2':3})  
    *arg = (111,222,1,2,3)   **kwargs = {'k11':'alex','k1':1,'k2':3}

3.2 References

3.2.1 Location parameter (calling function and passing parameter) (execution)

Input parameters strictly in place order when calling/executing functions

def func(a1,a2,a3):
    print(a1,a2,a3)
    
func(66,'alex',3)
3.2.2 Keyword Reference (Execution)

Keyword parameterization refers to the use of formal parameters in arguments.

def func(a1,a2):
    print(a1,a2)
    
func(a1=22,a2=8)

Keyword input and location reference can be mixed: the parameters of location input should be put in front, the parameters of keyword input should be put behind, and the number of parameters should be equal to the total number of parameters.

def func(a1,a2,a3):
    print(a1,a2,a3)
    
func(1,2,a3=3)
func(1,a2=2,a3=3)
func(a1=1,a2=2,a3=3)
func(a1=1,2,3)  # It's wrong.

def func(): Custom function open() These two built-in functions for python

​ pass len()

3.3 Key Points Related to Parameters

  • Define function

    def func(a1,a2):
      pass
    
    def func(a1,a2=None):  # For default values, the immutable type is written casually, if it is a variable type (pitted).
      pass
    
    def func(*args,**kwargs):
      pass

    For default values of functions, invariant types are generally used, and variable types are carefully used:

    If you want to set the default value for value to be an empty list:

    # Not recommended for use (there will be pits):
    def func(data,value = [])
    pass
    
    //Recommended use:
    def func(data ,value = None)
      if not value:
            value = []
    # Examples:
    def func(data,value = []
      value.append(data)
        return value
    
    v1 = func(1)   # v1 = [1]
    v2 = func(2,[11,22,33])   # v2 = [11,22,33,2]
    v3 = func(3)   # v3 = [1,3]

    Exercise questions:

    • What are the traps of def func(a,b=[])?

      If no parameter is passed to b, the default is the same address

    • Look at the results of code writing

      def func(a,b=[]):
          b.append(a)
          return b
      
      l1 = func(1)
      l2 = func(2,[11,22])
      l3 = func(3)
      
      print(l1,l2,l3)   # [1,3]   [11,22,2]   [1,3]
    • Look at the results of code writing

      def func(a,b=[]):
          b.append(a)
          print(b)
      
      func(1)    # [1]
      func(2,[11,22,33])   # [11,22,33,2]
      func(3)   # [1,3]
  • Call function

    Position parameters are in the first place and keyword parameters are in the second place.

Posted by zipdisk on Sat, 24 Aug 2019 01:47:01 -0700