SoFunction
Updated on 2024-10-30

Using Python Functions and Modules

1. The role of functions

Programming guru Mr. Martin Fowler once said, "Code comes in many bad flavors, and repetition is one of the worst! ".

Repetitive functionality can be encapsulated in a function module called a "function", which is a snippet of code that implements a single, or related, piece of functionality.

2、Define the function

The rules for defining functions are shown below:

  • The function code block starts withdef keyword followed by the function name and parentheses ().
  • The naming convention for function names is the same as the naming convention for variables.
  • returnkeyword is used to exit the function, optionally returning an expression to the caller.

The syntax is shown below:

def function name(parameter list):
    function body (math.)
    returnstatement

# Define a function and put two parameters in it #
def sum(arg1, arg2):
    # Returns the sum of 2 parameters..."
    total = arg1 + arg2
    return total


# Call the sum function
sumNum = sum(10, 20)
print(sumNum) // 30

3. Parameters of the function

In addition to the basic operations of defining a function and calling it, you can also use parameters in functions. Parameters of a function are simply variables that can be used in the body of the function. Unlike variables, such variables are passed in before the function body.

3.1 Default values of parameters

When a function is called with no arguments passed, the default arguments are used.

def printInfo(name, age=12):
    "Print any incoming strings."
    print("Name:", name)
    print("Age:", age)
    return


# Call the a function
printInfo(age=10, name="Little Red.")
print("------------------------")
printInfo(name="Little Ming.")

3.2 Variable parameters

By variable parameters, we mean that you can pass 0 or any number of parameters to the function when you call it.

# Use an asterisk expression to indicate that stamp can take 0 or any number of arguments
def printInfo(*stamp):

    # Variable parameters can be placed in a for loop to retrieve the value of each parameter
    for i in stamp:
        print(i)
    return


printInfo("Bowl of Chow.")
printInfo(1, 2, 3, 4, 5, 6, 7)
printInfo("hello", "hi")

4, with the module management function

within the same.pyfile if two function names are renamed due to thePythonThere is no concept of function overloading, so the later definition overrides the previous one, which means that only one of the two functions with the same name actually exists. This is where the role of modules comes into play.

PythonEach file in a module represents a module (module), it is possible to have functions with the same name in different modules, and when using a function you can use it via theimportThe introduction of the keyword into the specified module makes it possible to distinguish each function.

Example:Define two modules that aremodule1cap (a poem)module2, and then test the introduction process

module1

def printinfo():
    print("This is the printinfo function for the first module.")

module2

def printinfo():
    print("This is the printinfo function for the second module.")

Use the import keyword to introduce it directly:

import module1
import module2
# Introduced by module name plus . function name
()
()

Use the import... .as keyword to rename the introduction:

import module1 as m1
import module2 as m2
# can be introduced by renaming the name plus . Function names can be introduced by renaming the
()
()

Use from... .import... .as keyword to rename an introduced function:

from module1 import printinfo as p1
from module2 import printinfo as p2
# can be introduced by renaming the name plus . Function names can be introduced by renaming the
p1()
p2()

  • Worth noting:Here if you don't use as for renaming, because there are twoprintinfowould result in an error, so it needs to be renamed for the

__name__ == '__main__'usage
__name__bePythonis an implicit variable that represents the name of the module if you print the__name__,failing agreement__main__。

4.1 Example code

def printinfo():
    print("This is what's inside the function.")

print(__name__)
print("This is outside the module function.")

Output results:

# __main__
# It's outside the module function #

If theIf introduced as a module, the printed result is the name of the module (without path or extension).
sample code (computing)

import module

Output results:

module
This is outside the module function

The output is different at this point, simply put: in thein one's own eyesnamejust likemainHowever, in the eyes of other documentsnamejust likemodule

particle marking the following noun as a direct objectTransform it.

def printinfo():
    print("This is what's inside the function.")

printinfo()
if __name__=="__main__":
    print(__name__)
    print("This is outside the module function.")

Output results:

This is what's inside the function
__main__
This is outside the module function

When other files are introduced

import module

Output results:

This is what's inside the function

This is because other files introduced will not execute the code in the module if the if condition holds because the name of the module is module and not __main__.

__name__ == '__main__'In the actual scene is very useful, generally in the process of writing the module must be tested, in the import of the test results certainly can not also print out, if deleted, want to improve the module when you want to rewrite again, this time__name__ == '__main__'That's where it comes in.

5. Scope of variables

Please see the following code:

def test():
    b = "This is the function's variable."

    def test_nested():
        c = "This is a nested function variable."
        print(a)
        print(b)
        print(c)
    test_nested()


if __name__ == "__main__":
    a = "This is the global scope."
    test()

Understand the scope of variables based on this code

At this point in the functiontest_nestedCalling all three functions a,b,c in vivo will not report any error.

If you call the b variable outside the body of the function you will report a

print(b)
NameError: name 'b' is not defined

Error that variable b is undefined, because b is a local variable and is locally scoped and not accessible outside the body of the function

If there is a change in thetestA call to c inside a function reports

print(c)
NameError: name 'c' is not defined

The variable c is undefined in the error because c is in thetest_nestedInside the function, fortestfunctions are locally scoped, but fortestfunction inside thetest_nestedfunction, the variable b belongs to the nested scope in thetest_nestedfunction we are able to access it.

If you pass theglobalto promote b to a global variable, then calling the b variable outside the body of the function will print it properly

nonlocalThe keyword can only act on local variables and always looks for variables in the nearest upper level local scope

def outer():
    aa = 111

    def inner():
        nonlocal aa
        aa = 222
        print(aa)
    inner()
    print(aa)


outer()

Without thisnonlocalKeyword then function bodyinnerprintable222, function body outer print111If you add it, it will directly print the two 222

PythonTo find a variable, you search for it in the order of "local scope" - > "nested scope" - > "global scope" - > "built-in scope", which are Python's built-in identifiers. "The so-called "built-in scope" is Python's built-in identifiers, which have been used before.inputprintintetc. are all built-in scopes.

to this article on the use of Python letter and module of the article is introduced to this, more related to the use of Python letter and module content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!