Functions of Python Full Stack Road Series

Keywords: Python Lambda sublime Programming

function

Function is the most basic program structure that Python provides for maximizing code reuse and minimizing code redundancy.

  1. Functional Formula: Encapsulate a function code into a function, so that it does not need to be repeated in the future, just call the function.
  2. Object-Oriented: Classifying and encapsulating functions to make development "faster, better and stronger..."

The most important thing in functional programming is to enhance code reusability and readability

Created Functional Syntax

def function name (parameter):
    ...
    Function Body
    ...
    Return value

A simple example

# x is a parameter of function
>>> def num(x):
...  print(x)
...
# 123456 equals x
>>> num("123456")
123456

Return value of function

The return value of a function needs to use the keyword return. The return value is mainly used to accept the execution result of the function.

What I don't know in the process of learning can be added to me?
python learning communication deduction qun, 784758214
 There are good learning video tutorials, development tools and e-books in the group.
Share with you the current talent needs of python enterprises and how to learn python from zero foundation, and what to learn
>>> def re():
...   if 1==1:
...     return True
...   else:
...     return False
...
>>> re()
True

If the return value is not specified, then the default parameter None is returned.

In a function, when the return execution is complete, the code behind the return will not be executed

>>> def ret():
...  print("123")
...  return True
...  print("abc")
...
>>> ret()
123
True

Location parameters

The values of the incoming parameters are assigned in sequence.

Code

# x=== Formal parameters, there are several formal parameters, then the actual parameters will be passed several, except the default parameters.
def ret(x):
    print(x)
# Actual parameters of "Hello Word"
print(ret("Hello Word"))

results of enforcement

Hello Word

As shown in the figure:
[Picture upload failed. (image-9806dc-1565701887342)]

The values in ret parentheses are passed into the function ret to do the value of x, and the result is almost print("Hello Word").

Common parameter instance of the function: Send mail

def email(mail):
    import smtplib
    from email.mime.text import MIMEText
    from email.utils import formataddr

    msg = MIMEText('Mail content', 'plain', 'utf-8')
    msg['From'] = formataddr(["test",'asdasd@126.com'])
    msg['To'] = formataddr(["Leave",'asdasdasd@163.com'])
    msg['Subject'] = "theme"

    server = smtplib.SMTP("smtp.126.com", 25)
    server.login("wdfgfghfgh@126.com", "123456")
    server.sendmail('asdasdas@126.com', [mail,], msg.as_string())
    server.quit()

email("6087414@qq.com")

When this script is executed, mail will be sent to mailbox 6087414@qq.com.

** Note: ** The mailbox addresses above are all written casually. Please change them by yourself.

Specified parameters

>>> def ret(a,b,c):
...  print(a,"a")
...  print(b,"b")
...  print(c,"c")
...
>>> ret(b="bbb",a="aaa",c="ccc")
aaa a
bbb b
ccc c

The default is to enter the values of the function parameters in ret brackets in order, but if the values of the parameters are set in ret brackets, then they do not need to come in order.

Default parameters

If we define a value for a function when we create it, we will report an error if we do not fill in the value program when we call the function:

>>> def ret(x):
...  print(x)
...
>>> ret()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ret() missing 1 required positional argument: 'x'

If you want to solve this problem, you can specify a default value for the value of the function. The default value of the specified function needs to be specified in the def line. After formulation, you do not need to input the function value when calling the function.

>>> def ret(x="Hello Word"):
...  print(x)
...
>>> ret()
Hello Word
# If the value specifies the default value, the actual parameter replaces the formal parameter.
>>> ret("Pythoner")
Pythoner

If a default value is created for a function, then the parameter with the default value must be defined at the end, not before the value without the default parameter.

dynamic parameter

Dynamic parameters take the actual parameters received as a tuple, and each parameter is an element of the tuple.

The first dynamic parameter

Defining the first dynamic parameter requires adding a * sign before the parameter

>>> def ret(*args):
...  print(args,type(args))
...
>>> ret(11,22,33)
(11, 22, 33) <class 'tuple'>

The second dynamic parameter

To define the second dynamic parameter, we need to add two * signs before the parameter. When we pass the parameter, a key corresponds to a value, which corresponds to a dictionary key-value pair, and the type returned is the dictionary type.

Using two asterisks, parameters can be collected into a dictionary. The name of the parameter is the key of the dictionary, and the value of the corresponding parameter is the value of the dictionary.

>>> def ret(**kwargs):
...  print(kwargs,type(kwargs))
...
>>> ret(k1=123,k2=456)
{'k1': 123, 'k2': 456} <class 'dict'>

The third dynamic parameter

The third dynamic parameter, also known as omnipotence, is illustrated by the following examples:

>>> def ret(*args,**kwargs):
...  print(args,type(args))
...  print(kwargs,type(kwargs))
...
>>> ret(11,222,333,k1=111,k2=222)
(11, 222, 333) <class 'tuple'>
{'k1': 111, 'k2': 222} <class 'dict'>

Dictionary examples:

>>> def arg(**kwargs):
...  print(kwargs,type(kwargs))
...
>>> dic = {"k1":123,"k2":456}
>>> arg(k1=dic)
{'k1': {'k1': 123, 'k2': 456}} <class 'dict'>
>>> arg(**dic)
{'k1': 123, 'k2': 456} <class 'dict'>

Avoid modification of variable parameters

If we don't want to modify the parameter value inside the function to affect the value of the external object, we can use slicing to transfer the parameter.

#!/use/bin/env python

L = ['a', 'b']
def changer(L):
    L[0] = 0
print(L)
changer(L)
"""
['a', 'b']
[0, 'b']
"""
# changer(L[:])
"""
['a', 'b']
['a', 'b']
"""
print(L)

Parametric unpacking

In [2]: def f(a, b, c, d): print(a, b, c, d)

In [3]: args = (1, 2)

In [4]: args += (3, 4)

In [5]: f(*args)
1 2 3 4

Or use

def f(a, b, c, d): print(a, b, c, d)
args = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
f(**args)

Parametric Writing Location

In function calls: position parameter -"keyword parameter -" tuple form -"dictionary form
In the Header of Function: General Parameters - Default Parameters - Tuple Form - Dictionary Form

def func(name, age=None, *args, **kwargs):
    print(name, age, args, kwargs)

func('ansheng', 18, *(1, 2, 3), **{'blog': 'blog.ansheng.me'})

Global and local variables

Simply understand global variables and variables, global variables can be understood as variables defined in the current file, and local variables are variables defined in the function, as follows:

# qa
# global variable
n1 = 1
def num():
    # local variable
    n2 = 2
    print(n1)
    print(n2)
num()

Output results

C:\Python35\python.exe F:/Python_code/sublime/Day05/def.py
1
2

Defined global variables can be called in the function, but can not be modified in the function, local variables can not be directly called, if you want to modify global variables in the function, then you need to use keywords.``

n1 = 1
def num():
    n2 = 2
    global n1
    n1 = 3
    print(n1)
    print(n2)
num()

results of enforcement

C:\Python35\python.exe F:/Python_code/sublime/Day05/def.py
3
2

nonlocal statement

nonlocal is used to modify variables in nested scopes. Similar to global, it only needs to declare variable names in nested functions, but this variable name must already exist, otherwise it will be wrong. If the variable to be modified can not be found in scopes, it will not continue to search in global or built-in scopes. Look for it.

In [1]: def func1(arg1):
   ...:     n = arg1
   ...:     print(n)
   ...:     def func2():
   ...:         nonlocal n
   ...:         n += 1
   ...:     func2()
   ...:     print(n)
   ...:     

In [2]: func1(10)
10
11

Lambda expression

Lambda (Lambda expressions) expressions are anonymous functions created by lambda keywords. Lambda functions can be used wherever function objects are needed. Grammatically, they are limited to only one single expression.

Creating Functions Using Lambda Expressions

>>> f = lambda x,y : x + y
>>> f(1,2)
3

Using def to create functions

>>> def f(x,y):
...  return x + y
...
>>> f(1,2)
3

For simpler functions, we can create them by lambda, which has the advantage of shortening the number of rows.

Nested lambda and scope

def action(x):
    return (lambda y: x + y)

act = action(99)
print(act)
result = act(2)
print(result)

The output is:

<function action.<locals>.<lambda> at 0x1021e6400>
101

Lambda can also obtain variable names in any upper lambda:

action = lambda x: (lambda y: x + y)
act = action(99)
print(act)
result = act(3)
print(result)

The output is:

<function <lambda>.<locals>.<lambda> at 0x1029e6400>
102

Test questions

Topic 1

Brief description of the differences among common parameters, specified parameters, default parameters and dynamic parameters

Ordinary parameters are the parameters that the user fills in when calling the function, and the position of parameters must be consistent with the parameters.

The specified parameter is that the user does not need to fill in the position of the parameter in the function when calling the function. The specified parameter is the value corresponding to the parameter that needs to be formulated.

The default parameters can be written after the defined parameters. If the user calls the function without setting the parameters, the default parameters will be used. If the user specifies the parameters, the user specifies the parameters instead of the default parameters.

Dynamic parameters can accept any parameters input by users, including dictionary, list, tuple and other data types.

Question 2

Calculate numbers, letters, spaces, and other numbers in the incoming string

What I don't know in the process of learning can be added to me?
python Learning Exchange Button qun,784758214
//There are good learning video tutorials, development tools and e-books in the group.
//Share with you the current talent needs of python enterprises and how to learn python from zero foundation, and what to learn
def var(s):
    all_num = 0
    spance_num = 0
    digit_num = 0
    others_num = 0
    for i in s:
        # Detection Number
        if i.isdigit():
            digit_num += 1
        # Detecting Spaces
        elif i.isspace():
            spance_num += 1
        # Detect letters
        elif i.isalpha():
            all_num += 1
        else:
            # Other
            others_num += 1
    return ("Letter:",all_num,"Spaces:",spance_num,"number",digit_num,"Other characters",others_num)
num = var("21323 asd*%^*^% &*213asdasdasda sdasdasd")
print(num)

results of enforcement

C:\Python35\python.exe F:/Python_code/sublime/operation/Day05/c.py
('Letter:', 21, 'Spaces:', 3, 'number', 8, 'Other characters', 8)

Question 3

Write function to determine whether the length of the user's incoming object (string, list, tuple) is greater than 5, return True if greater than 5, and False if less than 5

# Define a function num
def num(x):
    # The value of the judgement function returns True if the length is greater than 5
    if len(x) > 5:
        return True
    # Otherwise return to False
    else:
        return False

ret = num(["asd","asdasd","asdasd","asdasd"])
print(ret)
ret = num("asdasdasd")
print(ret)

Question 4

Write a function that checks whether each element of the user's incoming object (string, list, tuple) contains empty content and returns False if it is empty

# Define a function num
def num(x):
    # Loop out everything in num
    for n in x:
        # Converting data types to strings
        n = str(n)
        # If there is a space, return to False
        if n.isspace():
            return False

ret = num(" ")
print(ret)

ret = num("asdasd")
print(ret)

ret = num(["asd","312",123," "])
print(ret)

Question 5

Write a function to check the length of the incoming list. If it is larger than 2, only the first two lengths of content are retained and the new content is returned to the caller.

def num(x):
    # If the length of the list is greater than 2, output the first two items of the list, or return an empty one.
    if len(x) > 2:
        return x[:2]
    else:
        return ""
print(num(["11","22","33"]))

print(num(["33"]))

Sixth topic

Write a function that checks for all odd-digit index corresponding elements of the incoming list or tuple object and returns them to the caller as a new list.

def num(x):
    # Define an empty list for receiving odd-digit elements
    resule = []
    # All element values in the circular output list
    for n in range(len(x)):
        # If the position in the list is odd, add the value to the resule list
        if n % 2 == 1:
            resule.append(x[n])
    # But what's in the resule list
    return resule

ret = num([11,22,33,44,55,66])
print(ret)

Topic 7

Write a function to check the length of each value passed into the dictionary. If it is greater than 2, only the first two lengths of content are retained and the new content is returned to the caller.

dic = {"k1": "v1v1", "k2": [1111,22,33,44]}

PS: value in a dictionary can only be a string or a list

Code

def dictt(x):
    # All key s in a circular dictionary
    for k in x.keys():
        # If the element k in the dictionary corresponds to the string type, the following judgment is made
        if type(x[k]) == str:
            # If the length of the element is greater than 2
            if len(x[k]) > 2:
                # Let this element be reassigned, and the new value retains only the first two of the original value.
                x[k]=x[k][0:2]
        # If the element type corresponding to k in the dictionary is a list, enter the following judgment
        elif type(x[k]) == list:
            # First, all the values in the list are for loops
            for i in x[k]:
                # Converting elements to strings
                string = str(i)
                # If the length of the element is greater than 2
                if len(string) > 2:
                    # Get the index value of the element
                    num = x[k].index(i)
                    # Delete this element first
                    x[k].pop(x[k].index(i))
                    # Then add a new element, which retains only the first two of the original elements.
                    x[k].insert(num,string[:2])
    # return the results
    return dic
ret = dictt(dic)
print(ret)
  • results of enforcement
C:\Python35\python.exe F:/Python_code/sublime/operation/Day05/h.py
{'k1': 'v1', 'k2': ['11', 22, 33, 44]}

If you are still confused in the world of programming, you can join our Python learning button qun: 784758214 to see how our predecessors learned! Exchange experience! I am a senior Python development engineer, from basic Python script to web development, crawler, django, data mining and so on, zero-based to the actual project data have been collated. To every Python buddy! Share some learning methods and small details that need attention. Click to join us. python learner gathering place

Posted by RoBoTTo on Wed, 14 Aug 2019 06:29:33 -0700