Python Programming--function design and invocation

Source: Internet
Author: User

I. Function definition and invocation

def function name ([parameter list]):     " " Notes " "     function Body

# Fibonacci number with output less than n >>def  fib (n): A,    b=1,1 while     a < N:         Print (a,end=")        A, a =b,a+b    print()> >FIB (3)1 1 2

Second, form participation in the actual parameter

In most cases, modifying the value of a parameter directly inside a function does not affect the argument

def AddOne (a):     Print (a)    a+=1    Print (a)>>a=3>>AddOne (a)34>>a3

How to modify function parameter values:

If a variable sequence is passed to the function,

and using subscripts or other methods to add, delete, and modify element values for a schedule sequence within a function,

The modified result can be reflected outside the function, that is, the arguments are modified accordingly

# Modify the value of a list element
def Modify (v): = v[0] + 1>>a=[2]>>print(a) [2] >>Modify (a)>>print(a) [3]
# add elements to a list def addlist (v,item):    v.append (item)>>a=[2]>>addlist (a,3)>> Print (a) [2,3]

Three, parameter type

python function parameters are mainly divided into: common parameters, default value parameters, key parameters, variable length parameters, etc.

You do not need to specify the type of the parameter when defining a function, which is determined by the argument type and the understanding and inference of the Python interpreter

Similarly, you do not need to specify the return value type of the function, as determined by the type of return value returned by the return statement

A null value of None is returned by default when a return statement is missing or a return statement is not executed

1. Default value parameter

When you call a function with a default value, you can not assign a value to the default value parameter, or you can replace its default value by displaying an assignment

When you define a function with a default value, the default parameter must appear at the far right of the function parameter list, and no non-default value parameter can appear to the right of any of the default value parameters

def function name (..., parameter name = default value):    function Body def say (message, time=1):    print(( message+") *times)

>>say.__defaults__
(1,)

2. Key parameters

Refers to how arguments are passed when a function is called, regardless of the function definition

Values can be passed by name by key parameters, and the argument order can be inconsistent with the parameter

def demo (a,b,c=5):    print(a,b,c)>>demo (3,7)3 7 5>> Demo (c=8,a=9,b=0)9 0 8

3. Variable length parameters

*parameter is used to receive any number of arguments and place them in a tuple

**parameter is used to receive multiple arguments in the form of an assignment, similar to a key parameter, and put it into the dictionary

defDemo (*P):Print(P)#putting an argument into a tuple>>demo (A)(The)#automatically converts a receive parameter to a dictionary when the function is calleddefDemo (* *p): forIteminchP.items ():Print(item)>>demo (x=1,y=2,z=3)('x', 1)('y', 2)('Z', 3)

4. Sequence unpacking when parameters are passed

You can use lists, tuples, collections, dictionaries, and other objects that can iterate as arguments.

With an asterisk in front of the argument name, the interpreter is automatically unpacked and passed to multiple univariate parameters

To ensure that the number of elements in an argument is equal to the number of formal parameters

defDemo (a,b,c):Print(a+b+c)>>seq = [A]>>demo (*seq)6#Word Typical, default by key unpacking>>dic={1:'a', 2:'b', 3:'C'}>>demo (*dic)6#Specifies that the package is unpacked by value>>demo (*dic.values ()) ABC

Iv. Scope of variables

Variables defined inside a function are usually local variables, and variables that are not part of any function are generally global variables

Try to avoid using global variables, slow references, and increase implicit coupling between different functions

If you want to modify the value of a variable inside a function that is defined outside the function, then this variable cannot be local.

defdemo ():GlobalX#declaring global VariablesX=3#Modifying the value of a global variableY=4#Local Variables    Print(x, y) ×=5#defining global variables outside of a functionDemo ()#call a function to modify the value of a global variablePrint(x) out:5Print(y)#local variables are automatically deleted when the function endsOut:NameError:name'y'  is  notdefineddelX#Delete Global Variables

Share global variables between different modules, define separate modules, pass global variables

# Define module a.pyGlobal_var = 0#  in module b.py import= 1#   Import= 2 in module c.py

function instance:

1, write functions, receive string parameters, return a tuple, where the first element is the number of uppercase letters, the second is a lowercase letter number

defCountstr (s): Result=[0,0] forChinchS:if 'a'<= CH <='Z': result[1] + = 1elif 'A'<= CH <='Z': result[0]+ = 1returnResulttmpstr='Abanv'Bign,littlen=countstr (TMPSTR)Print(Bign,littlen) out:3 2

2. Write a function that receives an integer list x and an integer n that are not equal to all element values, requiring the element with the value n as the fulcrum,

Put all elements less than n in the list in front of N, and all elements with values greater than n are placed behind n

1 ImportRandom2 defSortn (x,n):3     ifN not inchx:4         Print(N,'Is isn't an element of', X)5         return6     7i = X.index (n)#gets the index of the specified element in the list8X[0],x[i] = x[i],x[0]#exchange with the No. 0 element9Key =X[0]Ten      Onei =0 Aj = Len (x)-1 -      whilei<J: -          whileI < J andX[J] >=Key: theJ-=1 -X[I]=X[J]#find the first element that is smaller than the specified element from the back -          -          whileI < J andX[i] <=Key: +I+=1 -X[j]=x[i]#find the first element smaller than the specified element from the front +          AX[i] =Key at      -     returnX
1 x=list (range (1,10))2random.shuffle (x)3print(x) 4 Sortn (x,4)5print(x)

Python Programming--function design and invocation

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.