Data analysis with Python-2

Source: Internet
Author: User

Function

-If you want to reuse the same or very similar functions, write a function.
-function uses the DEF keyword declaration to return a value with the return keyword

def my_function(x, y, z=1.5):    if z > 1:        return z * (x + y)    else:        return z / (x + y)

-Returns None if no return at the end
-functions can have positional parameters and keyword arguments, keyword elaboration is usually used to specify default values or optional parameters, in the above code x and Y are positional parameters, and z is the keyword parameter, can be called in the following two methods

a = my_function(5,6,z=0.7)c = my_function(5,6,0.7)d = my_function(4,8)

-the keyword parameter must be located after the position parameter (if there is a positional parameter), you can specify the keyword parameter in any order
* Note: You can also pass positional parameters with keyword parameters. The previous example can be written as

 c = my_function(x=5,y=6,z=0.7)
namespaces, scopes, and local variables

-The function is happy to access the variables of two different scopes: global variable and local variable (local).
-python called namespaces
-The following function

def func():    a = []    for i in range(5):        a.append(i)

-After Func is called, the empty list A is created first, then 5 elements are added, and a is destroyed when the function exits
-If we define a as follows

a = []def func():    for i in range(5):        a.append(i)

-Although you can assign a global variable to a function, those variables must be declared as global variables with the GLOBALS keyword to

global a
Return multiple values
def f():    a = 5    b = 6     c = 7     return a,b,ca,b,c = f()print(a)print(b)print(c)

-The above code returns a ternary tuple
-You can also write the following code to return a dictionary

def f():    a = 5    b = 6     c = 7     return {"a":a,"b":b,"c":c}a= f()print(a)

Data analysis with Python-2

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.