Python Learning notes-functions

Source: Internet
Author: User

What is a function?

The term function is derived from mathematics, but the concept of "function" in programming is very different from the function in mathematics, and the function in programming has many different names in English. In basic it is called subroutine (sub-process or subroutine), in Pascal is called procedure (process) and function, in C only function, in Java is called method.

Definition: A function is a collection of a set of statements by a name (function name) encapsulated, in order to execute this function, just call its function name.

function (method, function):

1. Improve the reusability of the Code;

2. Make your code more concise

Third, the definition of functions in Python:

The definition function uses the DEF keyword, followed by the function name, and the function name cannot be duplicated

def SayHello ():          # function name     print('hello')      # function Body #函数不调用是不会被执行的SayHello ()   # function name parentheses call function

Parameters of the function:

Formal parameters: Parametric the memory unit is allocated only when called, releasing the allocated memory unit immediately at the end of the call. Therefore, the formal parameter is only valid inside the function.

Arguments: Arguments can be constants, variables, expressions, functions, and so on, regardless of the type of argument, and when making a function call, they must have a definite value in order to pass these values to the parameter. The parameter variable can no longer be used after the function call finishes returning the keynote function.

def Calc (A, b):  # formal parameters, formal parameter    #a, b. position parameter, required parameter     res=a*b      Print ('%s*%s=%s'% (a,b,res)) Calc (7,8)       # arguments , actual parameters 

Simply put, the parameter is the argument that the function receives, and the argument is the one you actually passed in.

defOp_file (file_name,conent=None):#default value parameter, it is not requiredf = open ('file_name','A +', encoding='UTF-8'# ' A + ' can read also can write F.seek (0)ifConent:#do not write for empty delegates, read for empty delegatesf.write (conent) F.flush ()Else: All_users=F.read ()returnAll_users#What results are returned after the function is calledF.close ()
Res=op_file (' A.txt ')
Print (RES)

Local variables: variables defined in the function, are local variables, can only be used inside the function, out of the function can not be used

Global variables: Variables that can be used by public variables

1. Unsafe, because everyone can change;

2. Global variables will always occupy the memory

 name= "  Zhang San   " #   global variable  #   If you want to change the global variable, first declare that the modified value is all variables  def   Sayname ():  global   name #global声明全局变量 name  =  "  John Doe  "  print  ( " name1  "  Span style= "COLOR: #000000" >,name) sayname ()  print  (  " name2  , name" 

The function of return:

1. Return the result of the function processing;

2. Immediately ends the function, the function encounters a return, and the function ends immediately

def h ():     # function, the return function is immediately over.     for  in range (5):        print(i)        if i==3:              return    # only one return is written, returning noneres=h ()
Print (RES)

ImportstringdefHR (PWD):#length 6-11    #Letters and Numbers    ifLen (PWD) >5 andLen (PWD) <12:        ifSet (PWD) & Set (String.ascii_letters) andSet (PWD) &Set (string.digits):Print('Password Legal')        Else:            Print('The password is illegal .')    Else:        Print('The password is illegal .')res=hr (' abc123 ') #函数里面如果没有return的话, default return NonePrint (res)

Determine if it is a decimal:

defIs_float (s): s=Str (s)ifS.count ('.') ==1: S_list=s.split ('.') Left=S_list[0] right=s_list[1]        ifLeft.isdigit () andRight.isdigit ():#Positive Decimals            returnTrueelifLeft.startswith ('-') andLeft.count ('-') ==1:#Judging if the minus sign is legal, is it possible to have a valid negative number            ifLeft.split ('-') [1].isdigit () andRight.isdigit ():#Judging legal negative decimals                returnTruereturnFalse#Print (is_float (' 1.5 '))

Constants: A constant value that defines the name of the variable to be capitalized

Josn strings: string with double quotes, no single quotes

Loads: The string is passed

Import JSON # The JSON string is a string f=open ('product.json', encoding='UTF-8'  ) Res=f.read () product_dic=json.loads (res)   #  Loads the JSON string into Python's data type print(product_dic.get ('product_info' ) ))

Load (): Send a File object that will read the file for you

Import JSON # The JSON string is a string f=open ('product.json', encoding='UTF-8'  )print# without S, benefit: no need to read again,

Dictionary converted to JSON

D={    'a':{        'Addr':'Beijing',        ' Age': 28    },    'b':{        'Addr':'Shanghai',        ' Age': 18}}FW=open ('User_info.json','W', encoding='Utf-8') Dic_json=json.dumps (d,ensure_ascii=false,indent=4)
#Dictionary converted to json,ensure_ascii display Chinese, indent=4 indent 4 spacesFw.write (Dic_json)

Dump

D={    'a':{        'Addr':'Beijing',        ' Age': 28    },    'b':{        'Addr':'Shanghai',        ' Age': 18}}FW=open ('User_info.json','W', encoding='Utf-8') json.dump (D.fw,ensure_ascii=false,indent=4)

The parameters of the function are not fixed:

* Non-required parameters, no parameter number limit, passed over the parameters placed in the Yenzuri

def Syz (*args):    # parameter group    print(args)    username=args[1]    pwd=args[2]syz () syz ('Huang','123 ','dasd')

Printing results:
(' Huang ', ' 123 ', ' DASD ')

**

def Sys2 (**kwargs):   # keyword parameter    print(Kwargs) sys2 () sys2 (Name= ' Nhy ', age=19) sys2 ('nhy')

Printing results:
{}
{"Name": ' Nhy ', "age" = 19}
Error

Small exercise:

ImportJSONdefOp_data (filename,dic=None):ifDic:#Write it inwith open (filename,'W', encoding='Utf-8') as Fw:json.dump (Dic,fw,ensure_ascii=false,indent=4)    Else: With open (filename,encoding='Utf-8') as fr:returnJson.load (FR) file_name='User_info.json'all_users=op_data ('User_info.json') forIinchRange (3): Choice= Input ('input: 1. Registration, 2 Delete')    ifchoice=='1': Username=input ('Username:') Password=input ('Password:')        ifUsername not inchAll_users:all_users[username]=password Op_data (file_name,all_users)elifchoice=='2': Username=input ('Username:') All_users.pop (username) op_data (file_name,all_users)

Python Learning notes-functions

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.