Functions of Python Basics

Source: Internet
Author: User

Python function of the foundation

First, Function basis

1 , function concept:

A function is to encapsulate a set of statements by a name (function name), and to execute this function, simply call the name of its functions

2 , the function of functions

(1) Reduce duplication of code

(2) to make the program extensible

(3) Make the program easier to maintain

3 , syntax definitions

def sayhi (x): #函数名 "' function description ' print (" Hello, I ' mnobody! ") return x #函数返回值sayhi () #调用函数

Keyword Description:

def: Create a function

Sayhi () : Name of function

print ("Hello, I ' m nobody!") : Function Body

return (): Return value

Sayhi () # calling Functions

4 , the execution process of the function

Defines a function that is not executed during the execution of the program, but only when the function is called by the program.

function Execution Procedure:

Def f1 (): print (123) return "111" #在函数中, once the return is executed, the function execution terminates the print (456) R = F1 () #只有调用函数时 immediately before the function executes the print (r) #打印函数返回值

5 , the return value of the function

(1) Returns the number of values is 0 o'clock, returns none

(2) The number of return values equals 1 o'clock, returns an object

(3) The number of returned values is greater than 1 o'clock, returning a tuple

Deftest (): Print ("First") #没有返回值deftest2 (): Print ("second") return 2 #返回值数量为1时deftest3 (): Print ("three") Return3, "dayi123", {"Age": +, ' name ': ' Yiliu '} #返回值数量多个时 one =test () tw o =test2 () three= test3 () print (one) print (three)

Second, the parameters of the function

1 basic parameters of a function

(1), general parameters

1 ) Parameter: The variable allocates the memory unit only when it is called, and immediately releases the allocated memory unit at the end of the call. Therefore, the formal parameter is only valid inside the function. Function call ends when you return to the keynote function, you can no longer use the shape parametric

2 arguments: Can be constants, variables, expressions, functions, and so on, regardless of the type of value of the argument, they must have a definite value when making a function call to pass these values to the parameter. It is therefore necessary to use the assignment, input and other methods to get the parameters to determine the value

def send (xxoo,content): #xxoo, content for the actual parameter print (xxoo,content) print ("Send message successfully:", xxoo,content) Retu RN Truesend (Dayi, is) #dayi and is parameter

(2), default parameters

def send (xxoo,content,xx= "OK"): #默认参数必须放在参数列表最后, you can have multiple default parameters print (xxoo,content,xx) print ("Send mail succeeded:", xxoo,content,xx Return truesend (' Dayi ', ' is ') #如果没有传参, then pass the default argument to send (' Dayi ', ' is ', ' niub ') #如果传递参数, the result is the pass parameter Number

(3), set parameters

The parameters passed by default are based on the order in which parameters can be scrambled:

def send (xxoo,content): print (xxoo,content) print ("Send mail succeeded:", Xxoo,content) return truesend (content= ' Dayi ', xxoo= ' is ') #将 ' Dayi ' to conttent, and ' is ' to be handed to Xxoo

2 , the dynamic parameters of the function

(1), dynamic parameters: can pass one or any number of parameters when the parameter is passed

1 ), add a "*" to the parameter

Function: The passed parameters will be placed in the tuple,

Application scenario: Passed parameters are in order

def FL (*args): # line parameter with * indicates dynamic parameter print (Args,type (args)) FL (one) Li = [P, "Dayi", "Liu"]fl (LI) # put "Li "As a whole to the tuple inside FL (*li) #加" * "To send elements of Li to the tuple inside FL (li,12) li2 =" Dayi123 "FL (li2) #不带 *, li2 whole into tuples, with" * ", will Each string in the Li2 is passed into the tuple, FL (*li2), respectively

2 ), add two "*" at the time of the transfer of the parameter

Function: The passed parameter will be put into the dictionary

Application scenario: Passed parameters are not in order

def f1 (**args): Print (Args,type (args)) F1 (n1= "dayi123", n2=24) #传参时必须传两个, a "KEY" one "value" dic = {' name ': "Dayi" , ' Age ': 18}f1 (kk=dic) #传参是把字典当做一个整体传进字典中f1 (**dic) #传参时将字典中的每一个值分别传进字典中

3 ), there are two "*" and a "* "

Function: Universal parameters, can pass a "*" parameter, but also can pass "* *" parameters

EF F1 (*args,**kwargs): Print (Args,type (args)) print (Kwargs) F1 (1,2,3,name= "Dayi", age=24) Tup = (22,33,44,55) dic = {' NA Me ': "dayi123", ' Age ': 23}f1 (*tup,**dic) F1 (yz=tup,cd=dic)

(2), using dynamic parameters to achieve the Format function

S1 = "I am {0},age{1}". Format ("dayi123", +) print (S1) s2 = "I am {0},age {1}". Format (*["dayi123") #传递列表中的参数, the front must be "*" Print (s2) s3 = "I am {name},age {age}". Format (name= "dayi123", age=24) print (s3) dic = {' name ': ' dayi123 ', ' age ': 24}s4 = ' I Am {name},age {age} '. Format (**dic) #将字典中参数传递给s4, you must add "* *" Print (S4)

(3), the function parameter is passed the reference

Def f1 (A1): A1.append (999) # function Arguments pass a reference to Li = [11,22,33,44]f1 (li) print (LI)

3 , global variables and local variables

Global variables are readable for all scopes, local variables are readable only for partial scopes, global variable declarations are capitalized, and global variables can be lists, dictionaries. Global variables can be modified through global, and if the global variables are dictionaries and lists, they can be modified, but cannot be re-assigned.

NAME = "Alex" #全局变量, all scopes are readable, the declaration of the global variable is capitalized #name = [123,456,789] #如果全局变量是列表字典, it can be modified but not re-assigned DEF FL (): Age = 1    8 Global name #修改全局变量, to re-assign a value to the globals, need to first global name = "123" #局部变量, only the current effect on the effective print (AGE,NAME) def f2 (): Age = Print (Age,name) FL () F2 ()

The defined string, number format global variables can no longer be directly modified in local variables, but defined lists, dictionaries and other global variables are directly modified in local variables:

names= ["Dayi", "Boy"]defchange_name (): names[0] = "Liu" Print ("Inside Func", names) print (names) change_name () print (names)

Example: Using function to implement login function

Def login (Username,password):     f = open ("db", ' R ')                #打开db. txt file, ' R ' stands for read     for line  in f:        line_list = line.split ("|")   #一行一行读取, use "|" Separation         if line_list[0] == username and  line_list[1] == password:             Return truedef register (Username,password):     f = open ("db", ' a ')               #打开db. txt file, ' A ' stands for append      temp =  "\ n"  + username +  "|"  + password    f.write (temp)                      #向db. txt write     f.close ()                          #关闭并生效def  main ():     t = input ("1: Login; 2: Register")     if t ==  "1":         user = input ("Please enter user name:")          pwd = input ("Please enter password:")         r  = login (USER,PWD)         if r:             print ("Login Successful")         else:             print ("Login Failed")      elif t ==  "2":         user = input ("Please enter user name:")     &nbSp;   pwd = input ("Please enter password:")         register ( USER,PWD) Main ()

Also, create a new Db.txt file, enter: dayi123|dayi123

Three or three USD (Trinocular) operations and lambda expressions

1 , ternary operations

If 1 ==1:name= "Liu" else:name= "SB" #等同于: name = "Liu" if 1 = = 1 Else "SB"

2 , lambda expression (anonymous function)

def f1 (A1,A2): return A1 + a2 + 100ret = F1 (10,12) print (ret) #等同于 F2 = lambda a1,a2:a1 +a2 + 100ret2 = F2 (10,12) print (r ET2)

3 , conditional judgments in brackets, and examples of loops:

A = range (+) print ([I-I in a if i<5])

The output is: [0, 1, 2, 3, 4]

Iv. recursion

1 , recursion:

Recursive algorithm is a direct or indirect process to invoke its own algorithm. In the computer programming, the recursive algorithm is very effective to solve a large class of problems, it often makes the description of the algorithm concise and easy to understand.

2 , Recursive algorithm features:

(1) Recursion is the invocation of itself in a procedure or function.

(2) When using a recursive strategy, there must be a definite recursive end condition called a recursive exit.

(3) Recursive algorithm is usually very concise, but the recursive algorithm is less efficient in solving problems. Therefore, the recursive algorithm is generally not advocated for the design of the program.

(4) in Recursive invocation in the process of the system for each layer of the return point, local amount, etc. to open up a stack to store. Too many recursion times can cause stack Overflow and so on. Therefore, the recursive algorithm is generally not advocated for the design of the program.

3 , recursive example-factorial

def func (num): if num = = 1:return 1 return num * func (num-1) x = func (7) print (x)

Five. higher-order functions

A variable can point to a function, which can receive a variable, and a function can receive another function as a parameter, a function called a higher order function.

#!/usr/bin/env python# author:dayi123def fuc (a,b,f): Return f (a) +f (b) #将a, b values given to function f processing and then return to add = Fuc (7,-10,abs) #将内置函数abs传递给fprint (ADD)


This article is from the "dayi123" blog, make sure to keep this source http://dayi123.blog.51cto.com/12064061/1917700

Functions of Python Basics

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.