Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python functions and modules

2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this article "Python function and module how to use", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "Python function and module how to use" article.

I. define a function

In Python, you can use the def keyword to define functions, and the naming rules are the same as those for variables. The argument passed to the function can be placed in parentheses after the function name, and after the function is executed, we can return a value through the return keyword.

The definition code is as follows:

Def fac (num): "factorial" result = 1 for n in range (1, num + 1): result * = n # returns the value return result II, the parameter of the function "

In Python, the parameters of a function can have default values and support the use of variable parameters, so Python does not need to support function overloading like other languages, because we can use it in many different ways when we define a function

Here are two small examples:

From random import randint def roll_dice (nasty 2): "Shake dice" total = 0 for _ in range (n): total + = randint (1,6) return total def add (axi0, blis0) Return a + 2 * b + 3 * c # if no parameter is specified, then use the default value to shake two dice print (roll_dice ()) # shake three dice print (roll_dice (3)) # function overload, when no function variable is specified Parameters can be passed in the order print (add ()) print (add (1)) print (add (1,2)) print (add (1,2,3)) # you can pass print (add (add 50, add 100, baked 200)) # or not print (add (clocked 50, baked 200)) if _ _ name__ ='_ main__': pass

The default value of the parameter is used when no value is passed in for the corresponding parameter.

When the number of parameters is uncertain, we can use variable parameters, as shown in the code below:

# the * before the parameter name indicates that args is a variable parameter def add (* args): total = 0 for val in args: total + = val return total # when calling the add function, you can pass 0 or more parameters print (add ()) print (add (1)) print (add (1, 2)) print (add (1, 2)) print (add (1, 3, 5, 7, 9)) 3. Manage functions with modules

Since Python does not have the concept of function overloading, the later definition function overrides the previous definition, which means that only one of the two functions with the same name actually exists.

Def foo (): print ('hello, Worldwide') Def foo (): what does the code below print ('goodbye, worldview') # output? Foo () if _ _ name__ = ='_ _ main__': pass # actual output goodbye, world!

When multiple people collaborate on team development, there may be multiple programmers on the team who define a function called foo, so how do you resolve this naming conflict?

Focus on how to avoid function coverage!

In Python, each .py file represents a module. We can have a function with the same name in different modules. When using the function, we can import the specified module through the import keyword to distinguish which module we want to use the foo function.

The code is as follows:

Module1.py def foo (): print ('hello, Worldwide') Module2.py def foo (): print ('goodbye, Worldwide')

Import module:

Test.py import module1 as m1import module2 as m2 m1.foo () m2.foo ()

Note: however, if the code is written as follows, then the last imported foo is called in the program, because the later imported foo overwrites the previously imported foo.

From module1 import foofrom module2 import foo # outputs goodbye, Worldwide, using the later imported module foo ()

It is important to note that if we import a module that can execute code in addition to defining functions, then the Python interpreter will execute this code when importing the module. In fact, we do not want to execute this code, so we put the executable code into the conditions shown below, so that unless we run the module directly, the code under if conditions will not be executed. Because only the name of the directly executed module is "_ _ main__".

Def foo (): pass def bar (): pass # _ _ name__ is an implied variable in Python that represents the name of the module # only the name of the module executed directly by the Python interpreter is _ _ main__if _ _ name__ = ='_ _ main__': print ('call foo ()') foo () print ('call bar ()') bar () import module3# When entering module3, it will not execute the code in the module when the if condition is established, because the name of the module is module3 instead of _ _ main__. Variable scope def foo (): B = 'hello' # Python you can redefine the function def bar () inside the function: C = True print (a) print (b) print (c) bar () # print (c) # NameError: name 'c' is not defined if _ _ name__ = =' _ main__': a = 100 # print (B) # NameError: name 'b'is not defined foo ()

Print the results:

one hundred

Hello

True

The above code executes smoothly and prints out 100s, hello, and True, but we notice that there are no variables an and b defined inside the bar function, so where do an and b come from.

We defined a variable an in the if branch of the above code, which is a global variable (global variable) that belongs to the global scope because it is not defined in any function.

In the above foo function, we define the variable b, which is a local variable (local variable) defined in the function, which belongs to the local scope and cannot be accessed outside the foo function; but for the bar function inside the foo function, the variable b belongs to the nested scope, and we can access it in the bar function.

The variable c in the bar function belongs to the local scope and is inaccessible outside the bar function.

Python looks for variables in order:

Search in the order of Local scope-nested scope-Global scope and built-in scope.

Built-in scope: Python built-in identifiers, input, print, int, etc., which we have used before, all belong to the built-in scope.

We want to change the value of the global variable a through a function call, but in fact the following code cannot.

The code is as follows:

Def foo (): a = 200print (a) # 200if _ _ name__ = ='_ _ main__': # where the variable value cannot modify the function local variable value a = 100foo () print (a) # 100

After calling the foo function, we find that the value of an is still 100. this is because when we write a = 200 in the function foo, we redefine a local variable named a, which is not the same variable as an in the global scope.

Because there is its own variable an in the local scope, the foo function no longer searches for an in the global scope. If we want to modify an in the global scope in the foo function

The code is as follows:

Def foo (): global an a = 200print (a) # 200if _ _ name__ = ='_ main__': a = 100foo () print (a) # 200

You can use the global keyword to indicate that the variable an in the foo function comes from the global scope.

Note:

In actual development, we should minimize the use of global variables, because the scope and impact of global variables are so extensive that unexpected modifications and use may occur.

In addition, global variables have a longer life cycle than local variables, which may cause the memory occupied by objects not to be garbage collected for a long time.

The above is about the content of this article on "how to use Python functions and modules". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report