Python learns the initial function

Source: Internet
Author: User

The purpose of the function: to solve the code redundancy, poor readability, poor scalability.

General format of the function:

#函数定义def Mylen (): "" "    calculates the length of the S1" ""    S1 = "Hello World"    length = 0 for    i in S1:        length = length+1    prin T (length) #函数调用  Mylen ()

definition :The DEF keyword begins with a space followed by the function name and parentheses (), and finally a ":".

DEF is fixed, cannot be changed, must be a continuous def three letters, can not be separated ... They are going to love each other together.

Space in order to separate the DEF keyword and function name, you must be empty (four tones), of course, you can empty 2, 3, or how much you want to empty, but normal people still empty 1.

Function Name: Functions can only contain strings, underscores, and numbers, and cannot begin with a number. Although the function name can be random, but we give the function name or to be as short as possible, and can express function function

Brackets: Must be added, do not ask why the parentheses, in short, with parentheses on the right!

Note : each function should have a corresponding description of the function and parameters, which should be written in the first line below the function. To enhance the readability of your code.

Call : the function name () Remember to add parentheses, okay?

function has no return value:

No return value:

#function DefinitiondefMylen ():"""calculate the length of a S1"""S1="Hello World"length=0 forIinchS1:length= Length+1Print(length)#function CallStr_len =Mylen ()#because there is no return value, the Str_len is none at this timePrint('Str_len:%s'%str_len)

Because there is no return value in the function.

Structure with return value: return [expression] End Function

#function DefinitiondefMylen ():"""calculate the length of a S1"""S1="Hello World"length=0 forIinchS1:length= Length+1returnlength#function CallStr_len =Mylen ()Print('Str_len:%s'%str_len)

The function return value can be more than one:
defret_demo1 ():" "return multiple values" "     return1,2,3,4defRet_demo2 ():" "returns multiple values of any type" "    return1,['a','b'],3,4Ret1=Ret_demo1 ()Print(RET1) Ret2=Ret_demo2 ()Print(Ret2)

Multiple values returned are returned by the organization Narimoto group, or can be received with multiple values.

Functions can have parameters:

#function DefinitiondefMylen (S1):"""calculate the length of a S1"""length=0 forIinchS1:length= Length+1returnlength#function CallStr_len = Mylen ("Hello World")Print('Str_len:%s'%str_len)

This function can calculate the length of the string more than "Hello World", can be in the function of the call is put into the string you want to calculate. The concept parameters and arguments are involved here. Our incoming "Hello World" is an argument, and the S1 in the function definition is a formal parameter.

There are multiple return values for a function, and you can infer that there are more than one incoming value for the function.

Position parameters:

(1) According to the location of the transfer parameter

def Mymax (x, y    ): # at this time x=10,y=20    if Else y     return  = Mymax (10,20)print(MA)

(2) Follow the key words

def Mymax (x, y    ): # at this point x = 20,y = Ten    Print (x,    y) if Else y     return  = Mymax (y = 10,x =)print(MA)

(3) position, keyword mixed transfer parameter

def Mymax (x, y    ): # at this point x = 10,y =    Print (x,    y) if Else y     return  = Mymax (10,y =)print(MA)

Note: The positional parameter must precede the keyword argument and can only be assigned one time for one parameter.

Default parameters: (this parameter will not change in most cases)

def " male " ):    "" " print student information function, because most of the students in the class are boys,        so set the default parameter sex's default value is    ' Male '" "    Print(name,sex) stu_info ('Alex') stu_info (  'Eva','female')

Focus: The default parameter is a mutable data type

def defult_param (a,l = []):    l.append (a)    print(l) defult_param ('  Alex') defult_param ('Egon')

In fact L is a collection of all incoming parameters.

Advanced form of parameter transfer: I can receive it no matter how you pass it. (*args and **kwargs)

*args (Receive location parameters, and organize Narimoto groups)

def mysum (*args):    = 0    for in  args:        the_sum+ =  I    return= MySum (1,2,3,4)print(the_sum)

**kwargs (Receive keyword parameters and organize into dictionaries)

def Stu_info (* *Kwargs)    :print(Kwargs    )print(kwargs['  name'],kwargs['sex'Alex  'male')

Python learns the initial function

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.