Basic points in python

巴扎黑
Release: 2017-07-18 13:32:17
Original
1198 people have browsed it

Basic overview of functions

Before learning functions, we have always followed: process-oriented programming, that is: implementing functions from top to bottom based on business logic. You can think about if the code for a certain function is in multiple Is it possible to write it only once if it is used in each place? How should the code be defined at this time. Observe the following case first:

while True:
if cpu utilization > 90%:
#Send email reminder
Connect to email server
Send email
Close the connection
                                                                                                                                                                                                                                                                                                   %:
#Send email reminder
Connection mailbox server
Send mail
Close connection

or above.
#def Send email (content)
#Send email reminder
Connect to email server
Send email
Close connection

while True:

if cpu Utilization rate> 90%:
Send email ('CPU alarm')

if Hard disk usage space> 90%:
Send email ('Hard disk alarm')

if Memory usage > 80%:
Send email ('Memory Alarm')

For the above two implementation methods, the second time must be better than the first time in terms of reusability and readability. It can reduce a large amount of code and development time. It can be defined in one place and called in multiple places. In fact, this is functional programming

The concept of functional programming:
When developing a program, a certain piece of code is required multiple times Use, but in order to improve writing efficiency and code reuse, code blocks with independent functions are organized into a small module. This is the function

Definition and call of the function


<1>Define function

The format of defining a function is as follows:

def function name():

Code demo: # Define a function that can complete the function of printing information
  def printInfo():
  print '---------------- --------------------------'
    print 'Life is short, I use Python'
    print '---------- --------------------------'




The definition of function mainly has the following points:


 

• def: keyword representing a function • Function name: the name of the function, the function is called according to the function name when calling

 • Function body: performed in the function A series of logical calculations or the functional content of the function.

 • Parameters: Provide data for the function body

 • Return value: After the function is executed, data can be returned to the caller.

##<2>Call the function
After defining the function, it is equivalent to having a code with certain functions. To make these codes executable, you need to call it (note that the content inside will not be executed when defining the function) Calling the function is very simple, and the call can be completed through function name ()
demo:
 #After defining the function, the function will not be executed automatically. You need to call it.printInfo()

##<3>Function Document Description

Example:

>>> def test(a,b):
... "Used to complete the sum of 2 numbers"

... print("%d"%(a+b))

...
>>> >>> test(11,22)33 Execute, the following code>>> help(test)

You can see the relevant instructions of the test function

========== ====================================

Help on function test in module __main__:

test(a, b)
Used to complete the sum of 2 numbers
(END)

=============================================

Function parameters-return value

<1> Define a function with parameters
Examples are as follows:
def addnum(a, b):
c = a+b
  print c
<2> Call a function with parameters
Take calling the add2num(a, b) function above as an example:

 def addnum(a, b):
  c = a+b
  print c

  add2num(11, 22) #When calling a function with parameters, you need to pass the data in parentheses

 Small summary:
 • Small when defining The parameters in parentheses, used to receive parameters, are called "formal parameters"
• The parameters in parentheses when called, used to pass to the function, are called "actual parameters"

ps: There will be a separate blog explaining function parameters in detail later


##<3> Functions with return values The following example:

def add2num(a, b):
c = a+b
return c 
The return value example of the saved function is as follows:
 #Define function

 
def add2num(a, b):
Return a+b

#Call the function and save the return value of the function
result = add2num(100,98)

 

 #Because result has saved the return value of add2num, you can use it next
 print result Result:
 
198


In python we can return multiple values >>> def divid(a, b):
 ... shang = a//b
 ... yushu = a%b
 ... return shang, yushu
 ...
 >>> sh, yu = divid(5, 2)
 >>> sh
 5
 >>> yu
 1

The essence is to use tuples

Functions can be combined with each other depending on whether they have parameters and whether they have a return value. There are 4 types in total
 • No parameters, no return value
 • No parameters, no return value
 • With parameters and no return value
 • With parameters and return value

 <1>Functions without parameters and no return value
  Such functions cannot be accepted Parameters and no return value. Generally, for functions similar to printing prompt lights, use this type of function
 <2>Function without parameters and return value
 This type of function cannot accept parameters, but You can return certain data. In general, like collecting data, you use this type of function
 <3>Function with parameters but no return value
 This type of function can receive parameters, but cannot return data. Under normal circumstances, when setting data for certain variables without requiring results, use such functions
 <4>Functions with parameters and return values
  Such functions can not only receive parameters, but also return A certain data, in general, like data processing and applications that require results, use this type of function

Short summary

• The function depends on whether there are parameters, whether there are Return values ​​can be combined with each other
 • When defining a function, it is designed based on actual functional requirements, so the function types written by different developers are different
 • Whether a function has a return value depends on whether there is one return, because only return can return data
• In development, functions are often designed according to needs whether they need to return a value
• There can be multiple return statements in a function, but as long as one return statement is executed, then It means that the call of this function is completed
 •
Try not to repeat the name of the function in a program. When the function name is repeated, the later one will overwrite the previous one (Note: Do not repeat the variable name, it will also be overwritten. Override)

Nesting of functions

def testB():
 print('---- testB start----')
 print('This is testB The code executed by the function...(omitted)...')
 print('---- testB end----')


def testA():

 print('---- testA start----')

 testB( )

## print('---- testA end----')

Call

testA()

Result:

---- testA start----
---- testB start----
Here is the code executed by the testB function...(omitted)...
---- testB end----
---- testA end----

Small summary •
One function calls another function, This is the so-called Function nested calling   •
If another function B is called in function A, then all the tasks in function B will be executed first before returning to the previous function. The position where secondary function A is executed

Case of function nesting:

 1. Write a function to find the sum of three numbers

 2. Write a function to find the average of three numbers


 
# Find the sum of three numbers 
def sum3Number(a,b, c):
Return a+b+c # The return can be followed by a numerical value or an expression

 

# Complete the average of 3 numbers 
def average3Number(a,b,c):

  

# Because the sum3Number function has already completed the sum of three numbers, it only needs to be called
   # That is, the three received numbers can be passed as actual parameters   
sumResult = sum3Number(a,b,c)
   aveResult = sumResult/3.0
    return aveResult

 

# Call the function to complete the average of 3 numbers

 

result = average3Number(11,2,55)

 print("average is %d"%result)

Local variables and global variables of the function

Local variables

Example:

In [8]: def text1():
...: a = 200
                                                                                                                                                                                                                                                                                       . .: ​ ​ print("text1----%d" %a)
​ ​ ​ ​ ​...:

​ ​ ​ ​ ​ ​ ​ ​ ​​ ​ ​ ​ ​ ​ ​ ​ ​ print("text1----%d" ​ ​##                                                                                                                                                                                                                                             …: # Text1----200
After modification
text1----300

In [11]: text2()
text2-----400

 

Summary

  • Local variables are variables defined inside the function

   • Different functions can define local variables with the same name, but using different ones will not have any impact
  • The role of local variables. In order to temporarily save data, variables need to be defined in the function for storage. This is its role.

Global variables


Concept: If a variable can be used in a function or in other functions, such a variable is a global variable

 

 Example:  # Define global variables  In [12]: a = 250  In [13]: def text1 ():

                                                                                                                                                            ’ ’ s ’ s ’s ’ s ’s ’ ​ ’’ ​ ’ to ​​…: ​ ” print("----text1----%d" %a)

                          …:      ;   ----text1----250

In [16]: text2()
When:

In [23]: a = 250

# Global variable In [24]: def text1(): .. .: ​ ​..: ​
​ # Local variable ​ ​ ​ ​ ...: ​ ​ ​ a = 666

​ ​ ​ ​ ...: ​ ​ ​ print("----text1----%d" %a)

...:
  In [25]: def text2():    ...:    print("----text2----%d" %a)
   .. .:

  In [26]: text1()  ----text1----521   ----text1----666

  In [ 27]: text2()
   ----text2----250

  In [28]:

 

  Summary:

  • Variables defined outside a function are called global variables

   • Global variables can be accessed in
all

functions

   • If the name of the global variable is the same as the name of the local variable, then Local variables are used, a little trick to help the powerful but not the local snake

 Modify the global variable inside the function:
In [31]: a = 250
In [32]: def text1(): ...: a = 520
print("----text1----%d" %a )

In [33]: In [33]: def text2(): ...: global
a
...: a = 666
  ...:      print("----text2----%d" %a)
                   through No function is called


In [35]: print(a)
250

In [36]: # Call text1

In [37]: text1()
----text1----520

In [38]: # Print again---->

  In [39]: print(a)
  250

  In [40]: # Found that the value has not been modified

  In [41 ]:
# Call text2

  In [42]: text2()   ----text2----666

  In [43]:
# Print a

again   In [44]: print(a)   666

  In [45]: # The value has been modified
An object of the same variable


 
The difference between a mutable type global variable and an immutable type global variable-modified inside a function


  

ps: There will be a blog later that will explain the concepts of variable types and immutable types in detail
  Example: -------> Immutable type: In [46]: a = 6
In [47]: def demo(): ...: a += 1 ...: print (a)

...:

In [48]: demo() Error message: ------------- -------------------------------------------------- -----------

   UnboundLocalError          Traceback (most recent call last)

    in ()   ----> 1 demo() # 3

   UnboundLocalError: local variable 'a' referenced before assignment

   ----------------------------- -------------------------------------------
Note:Obviously it cannot be modified

------->Variable type:

In [49]: a = [1,]

In [50]:

In [50]: def demo():
...: a.append(2)
...: print(a)
. ..:

   In [51]: demo()
   [1, 2]

   In [52]: a
   Out[52]: [1, 2]

When a function is called, the value of the list is modified inside the function when the function is executed - and also changed when printed externally.
Summary:

  ○ If you modify a global variable in a function, you need to use global for declaration, otherwise an error will occur
  ○ Do not use global declaration in a function The essence of global variables that cannot be modified is that cannot modify the point of global variables, that is, cannot point global variables to new data. ○ ○ For global variables of
immutable type , the data pointed to by cannot be modified , so if global is not used, cannot modify the global variable.  ○ For global variables of
variable type, the data they point tocan be modified, so global can also be modified when global is not used variable.

The above is the detailed content of Basic points in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!