python learns day7-function 02+job

Posted by ThunderAI on Tue, 07 Dec 2021 23:36:44 +0100

python learning day7-function 02+function application job

1. Nested Functions

Nested functions: Functions defined within a function that encapsulate-hide data (nested functions are not accessible externally). Nested functions allow us to avoid duplicate code within subfunctions.
Operation:
1. Definition of Nested Functions

#Definition of test nested function
def outer():
    print("outer running")

    def inner():#The inner body is contained in the outer body and is a nested function
        print("inner running")

    inner()

outer()

Run result:
2. Use nested functions to avoid duplicate code

#Test using nested functions to avoid duplicate code
def printChinsename(name,familyname):
    print("{0}{1}".format(familyname,name))

def pritEngelishname(name,familyname):
    print("{0}{1}".format(name,familyname,))

printChinsename("Small Five","Zhao")
pritEngelishname("six","seven")
#Use nested functions instead of the two above functions

def printName(isChinese,name,familyname):
    
    def inner_print(a,b):
        print("{0}{1}".format(a,b))
    if isChinese:#Add a judgment isChinese
        inner_print(familyname,name)
    else:
        inner_print(name,familyname)

printName(True,"Small Five","Zhao")
printName(False,"six","seven")

Run result:

2. nonlocal keywords

Nonlocal is used to declare outer local variables, and modifications to outer variables within nested functions require nonlocal declarations.
Globals are used to declare global variables. Change the value of a global variable within a function and declare it using the globalkeyword.

Action: Test parameter changes using nonlocal and global declarations

#Testing nonlocal, global keywords
a=100#global variable

def outer():
    b=200#Outer Local Variables
    def inner():
        nonlocal b#Declare external local variable b
        print("inner b:",b)
        b=20
        global a#Declare global variable a
        a=300
    inner()
    print("outer b:",b)#Modifications to external function local variables
outer()
print("a:",a)

Run result:

3. LEBG Rules

When python looks for Name, it looks for it according to the LEBG rule

Local—Enclosed—Global—Built in
Loca refers to the method inside a function or class
Enclosed refers to a nested function (a function contains another function, a closure)
Globals are Global variables in modules
Built in refers to the special name python has reserved for itself.

Action: Test LEBG rules for finding "names"
By commenting out several "str s" in turn and observing the printed output, you can understand the search order of LEBG.

#Test LEBG, comment out str one time, look at the location of the print desk, you can understand the search order of LEBG
str="global"#Third Output Location
def outer():
    str="outer"#Location of the second output

    def inner():
        str="inner"#First Output Location
        print(str)
    inner()
outer()

The result of the last run is a special name python has reserved for itself, as follows:

4. Practical Operations

1. Define a function to reverse the output of an integer, such as: input 2345, output 5432.
Analysis: After defining the function, use the str() built-in function to change the input integer to string format, and then use the concept of slicing to rewrite the input integer output.

def f1(n):
    a=str(n)
    b=a[::-1]#String Slice
    print(a)
    print(b)
f1(2345)

Run result:

2. Write a function that calculates the following columns: m(n)=1/2+2/3+3/4+...n/n+1.
Analysis: Recursive functions can be used to compute this column.

n=int(input("Please enter an integer:"))
def f1(n):
    s=n/(n+1)
    if n==0:
        return 0
    else:
        return s+f1(n-1)#Call your own function to be a recursive function
        n=n-1
print(f1(n))

Operation result:


3. Enter the coordinates of the three vertices of the triangle and calculate the area of the triangle if they are valid. If not, prompt.

import math

def isvalid(a=0.0, b=0.0, c=0.0):
    """Determines whether three edges meet the definition of a triangle: the sum of any two sides is greater than the third side or the difference between any two sides is less than the third side"""
    side = [a, b, c]
    side.sort()
    if side[0] + side[1] > side[2] or side[2] - side[1] < side[0]:
        return True
    else:
        return False


def calculate_area():
    """Gets the three vertex coordinates of a triangle and calculates its area"""
    x1, y1 = map(int, input('Please enter the first vertex coordinate:').split())
    x2, y2 = map(int, input('Please enter the first vertex coordinate:').split())
    x3, y3 = map(int, input('Please enter the first vertex coordinate:').split())

    # Calculate Three Edge Lengths
    side1 = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
    side2 = math.sqrt((x1 - x3) ** 2 + (y1 - y3) ** 2)
    side3 = math.sqrt((x2 - x3) ** 2 + (y2 - y3) ** 2)

    # Call the isvalid() function to determine if a triangle can be formed
    if isvalid(side1, side2, side3):
        # Calculate Half Perimeter
        s = (side1 + side2 + side3) / 2
        # Calculate area
        area = (s * (s - side1) * (s - side2) * (s - side3)) ** 0.5
        print('The area of a triangle is:{:.2f}'.format(area))
    else:
        print('Invalid coordinates to form a triangle')


if __name__ == '__main__':
    calculate_area()

Run result:

4. Enter a number of milliseconds and change that number to hours, minutes, seconds.

ms=int(input("Please enter a millisecond:"))
def Time():
    s=ms/1000
    m=s/60
    h=m/60
    print("{0}Seconds,{1}Minute,{2}hour".format(s,m,h))
Time()

Run result:

The python basic learning function content summary is complete, learn python the seventh day, go!

Topics: Python Back-end