The base point in Python

Source: Internet
Author: User
Tags define local types of functions

Basic Overview of functions

Before learning the function, always follow: process-oriented programming, that is, according to the business logic from the top to the bottom of the implementation of functions, you can think about if there is a feature of the code is used in multiple places can be written only once? How the code at this point is defined. First look at the following cases:

While True:
If CPU utilization > 90%:
#发送邮件提醒
Connecting to a Mailbox server
Send mail
Close connection

If HDD uses space > 90%:
#发送邮件提醒
Connecting to a Mailbox server
Send mail
Close connection

If memory consumption > 80%:
#发送邮件提醒
Connecting to a Mailbox server
Send mail
Close connection

The contents of each if condition statement in the code above can be extracted from common examples:

def send mail (content)
#发送邮件提醒
Connecting to a Mailbox server
Send mail
Close connection

While True:

If CPU utilization > 90%:
Send mail (' CPU alert ')

If HDD uses space > 90%:
Send mail (' HDD alert ')

If memory consumption > 80%:
Send mail (' Memory alarm ')

For the above two implementations, the second is necessarily better than the first reusability and readability, you can reduce the amount of code, reduce development time, a definition, multiple calls, in fact, this is functional programming

The concept of functional programming:
When you develop a program, you need a block of code to use it multiple times, but in order to improve the efficiency of writing and the reuse of code, the code blocks with independent functions are organized into a small module, which is the function

Definition and invocation of functions

<1> defining functions
The format of the definition 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 a function has the following main points:

  def: The keyword that represents a function • Function name: The name of the function, called when the function is called according to the function name
• Function Body: A series of logical computations in a function or the function contents of the functions.
• Parameters: Provide data for the function body
• Return value: Once the function has finished executing, it can return data to the caller.

<2> calling functions
Once a function is defined, it is equivalent to having a code with some functionality that you want to be able to execute and call it (note that the contents of the function are not executed when you define it)
The calling function is simple, with the function name () to complete the call

Demo

# Once the function is defined, the function is not automatically executed and needs to be called before it can be
Printinfo ()


Document description of the <3> function
Cases:
>>> def Test (A, B):
... "To complete the sum of 2 numbers."
... print ("%d"% (a+b))
...
>>>
>>> Test (11,22)
33
execution, the following code
>>> Help (Test)

To see a description of the test function

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

Help on function test in module __main__:

Test (A, B)
Used to complete the sum of 2 numbers
(END)

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

parameter of function-return value

<1> defining a function with parameters
Examples are as follows:
 Def addnum (A, B):
c = a+b
Print C
<2> calling a function with parameters
To invoke the Add2num (a, B) function above, for example:

  Def addnum (A, B):
c = a+b
Print C

  Add2num (one, all) #调用带有参数的函数时, you need to pass the data in parentheses

Small summary:
• Define the parameters in parentheses, which are used to receive parameters, called "Formal parameters"
• Arguments in parentheses in the call, used to pass to the function, called "arguments"

  PS: There will be a separate post on the function parameters of the blog


<3> functions with return values
The following example:
   Def add2num (A, B):
c = a+b
Return C
  
An example of the return value of a Save function is as follows:
#定义函数


  Def add2num (A, B):
Return a+b

   #调用函数, by the way, save the return value of the function
   result = Add2num (100,98)

  #因为result已经保存了add2num的返回值, so you can use it next
Print result
Results:
  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 the use of tuples


function According to whether there are parameters, there is no return value, can be combined with each other, a total of 4
• No parameter, no return value
• No parameter, no return value
• With parameters, no return value
• With parameters, return values


<1> function without parameters, no return value
Such functions, which cannot receive parameters, nor return values, are normally printed with a function similar to the indicator light, using such functions
<2> functions with no parameters and return values
This kind of function, cannot receive the parameter, but can return some data, generally, like collects the data, uses this kind of function
<3> functions with parameters and no return values
Such functions, can receive parameters, but can not return data, in general, set the data for some variables without the result, use such functions
<4> functions with parameters and return values
Such functions, not only to receive parameters, but also to return some data, in general, such as data processing and require the results of the application, with such functions
Small summary


• Function According to whether there are parameters, there is no return value can be combined with each other
• When defining a function, it is designed according to the actual functional requirements, so different types of functions are written by various developers
• If a function has no return value, see if there is return, because only return returns the data
• In development, it is often necessary to design functions based on requirements without returning values
• There can be multiple return statements in a function, but as long as a return statement is executed, it means that the function's call is complete
• The name of the function in a program should not be repeated, when the function name is repeated, the back will overwrite the front (note: Also do not repeat with the variable name will be overwritten)

Nesting of functions

Def TESTB ():
Print ('----testb start----')
Print (' Here is the code that the TESTB function executes ... (omitted) ... ')
Print ('----testb end----')


Def TestA ():

Print ('----testA start----')

TESTB ()

Print ('----testA end----')

Call

TestA ()


Results:
----TestA Start----
----TESTB Start----
Here is the code that the TESTB function executes ... (omitted) ...
----TESTB End----
----TestA End----

Small Summary :
One function calls another function , which is called a function nested call
If another function B is called in function A, then the task in function B is executed before returning to the position where function A was last executed.

Examples of nested functions:

1. Write a function that asks for three numbers and
2. Write a function to find the average of three numbers


  # ask for 3 numbers and
  def sum3number (a,b,c):
return A+b+c # The back of a return can be a numeric value, but also an expression

  # Complete the averaging of 3 numbers
 def average3number (a,b,c):

    # because the Sum3number function has completed 3 numbers on the same, so just call to
# that is, the received 3 number, as an argument to pass
    Sumresult = Sum3number (a,b,c)
Averesult = sumresult/3.0
Return Averesult

  # Call function, finish averaging 3 numbers

  result = Average3number (11,2,55)

Print ("Average is%d"%result)

Local variables, global variables for functions

Local variables

Example:
In [8]: Def text1 ():
...: a = 200
...: Print ("Text1----%d"%a)
...: Print (after "modified")
...: a = 300
...: Print ("Text1----%d"%a)
...:

In [9]: Def text2 ():
...: a = 400
...: Print ("Text2-----%d"%a)
...:

In [ten]: Text1 ()
Text1----200
After modification
Text1----300

In [All]: Text2 ()
Text2-----400

 Summarize
• Local variables, which are variables defined inside the function
• Different functions can define local variables of the same name, but each one will not have an effect
• The role of local variables, in order to temporarily save the data need to define variables in the function to be stored, which is its role

Global variables

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

  

Example:
# define Global Variables
In []: a = 250

in [+]: Def text1 ():
...: Print ("----text1----%d"%a)
...:

in [+]: def text2 ():
...: Print ("----text2----%d"%a)

...:

In []: Text1 ()
----TEXT1----250

in [+]: Text2 ()
----TEXT2----250

  

  When local variables and global variables have duplicate names:
In [total]: a = $ # global variable

In []: Def Text1 ():
...: # Local Variables
...: a = 521
...: Print ("----text1----%d"%a)
...: # Local Variables
...: a = 666
...: Print ("----text1----%d"%a)
...:

in [+]: def text2 ():
...: Print ("----text2----%d"%a)
...:

in [+]: Text1 ()
----TEXT1----521
----TEXT1----666

in [+]: Text2 ()
----TEXT2----250

In [28]:

 Summarize:
• Variables defined outside the 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 the local variable is used, the small tip of the strong dragon does not press local bully

   to modify a global variable inside a function:
in [+]: a = 250

in [+]: Def text1 ():
...: a = 520
...: Print ("----text1----%d"%a)

In [33]:

in [+]: def text2 ():
...:GlobalA
...: a = 666
...: Print ("----text2----%d"%a)
...:

In [34]:# No functions are called

in [+]: print (a)
250

In [36]:# Call Text1

In [PNS]: Text1 ()
----TEXT1----520

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

In [All]: print (a)
250

In [40]:# The Discovery value has not been modified

In [41]:# call Text2

In [All]: Text2 ()
----TEXT2----666

In [43]:# Print again a

in [+]: print (a)
666

In [45]:# values have been modified
     Summary:
    • If you modify a global variable in a function, you will need to declare it using global, otherwise it would be equivalent to redefining an object of the same variable within the function (without passing arguments)

 For--Variable type global variables-and-immutable types global variables-differences in function modifications

    PS: Later there will be a blog detailing the concept of mutable types and immutable types
Example:-------> Immutable types:
in [+]: a = 6

in [+]: Def demo ():
...: A + = 1
...: print (a)
...:

In []: Demo ()

Error message:
---------------------------------------------------------------------------
Unboundlocalerror Traceback (most recent)
<ipython-input-48-00cf94af4371> in <module> ()
----> 1 demo ()

<ipython-input-47-6e1d5ad81f64> in Demo ()
1 def demo ():
----> 2 A + = 1
3 Print (a)
4

Unboundlocalerror:local variable ' A ' referenced before assignment

--------------------------------------------------------------------------
Note: Obviously, it is not allowed to modify

-------> Variable types:

in [+]: a = [1,]

In [50]:

in [+]: Def demo ():
...: A.append (2)
...: print (a)
...:

In [Wuyi]: Demo ()
[1, 2]

In []: 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 when external printing occurs.
Summarize:

0 If you modify a global variable in a function, you need to declare it using global, or else error
0 is You cannot modify the global variable's point to , which is .
0 for a global variable immutable type , the data pointed to by its , so modify global variables when you do not use global.
0 for a global variable of mutable type , the data can be modified because it refers to , so when you do not use global You can also modify global variables.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.