Getting started with function usage in python and getting started with python
This article describes in detail the usage of functions in Python programming, and has good reference value for learning Python programming. The specific analysis is as follows:
I. Function Definition:
In Python, the def keyword is used to define a function. The function includes the function name and parameters. The return type is not required. Python can return any type:
# A function without return values returns None def run (name): print name, 'runing' # The function body statement starts from the next line, and the first line must be indented> run ('xiaoming') xiaoming runing> print run ('xiaoming') xiaoming runing None # if there is no ruturn statement, the function returns None # The parameter def run (name) with the returned value: return name + 'runing' >>> r = run ('xiaoming') >>> r xiaoming runing
Ii. Document string:
In Python, annotations are represented by #, and no multi-line annotations are found at the moment. However, you can use multiple lines of strings to write a function:
Def run (name): "print somebody runing" "# The first line written in the function body is the document string print name, 'runing'
You can use _ doc _ to view the document string content of the function.
>>>run.__doc__ print somebody runing
Iii. parameters:
The parameter list of Python functions can be any number. When calling a function, you can use location binding or keyword binding to confirm the parameter corresponding to the input variable!
The Code demonstrated above can be regarded as location binding.
Next let's take a look at the keyword binding:
Def run (name, age, sex): print 'name: ', name, 'Age:', age, 'sex: ', sex >>> run (age = 23, name = 'xiaoming', sex = 'boys') # name: xiaoming age: 23 sex: boy
A parameter cannot be bound by both location and keyword in one call.
def run(name,age,sex): print 'name :',name,'age:',age,'sex:',sex >>> run('xiaoming',name='xiaoming',sex='boy') SyntaxError: non-keyword arg after keyword arg
When a function is called, if the first parameter is bound with a keyword, the following parameters must also be bound with a keyword!
Default parameters:
Def run (name, age = 20, sex = 'girl '): print name, age, sex >>> run ('nana ') nana 20 girl >>> run ('nana ', 23) nana 23 girl >>> run ('gg', 'boys') # bind the position to use. Therefore, python binds 'boys' to age instead of gg boy girl on sex. >>> run ('gg ', sex = 'boys') # bind mixed keywords, can achieve the desired effect gg 20 boy
1. If a function parameter contains a default parameter, all parameters after this default parameter must be the default parameter; otherwise, the following error occurs: SyntaxError: non-default argument follows default argument exception.
def run(name,age=10,sex): print name ,age ,sex SyntaxError: non-default argument follows default argument gg 23 boy
Several exceptions
def run(name,age,sex='boy'): print name,age,sex >>>run()#required argument missing >>>run(name='gg',23)#non-keyword argument following keyword >>>run('gg',name='pp')#duplicate value for argument >>>run(actor='xxxx')#unknown keyword
# The first case is the loss of parameters.
# The second case is: If keyword binding is used for the first case, keyword binding must be used for all the subsequent cases.
# Case 3: You cannot bind the location with the keyword at the same time in one call.
# Case 4: keywords outside the parameter list cannot be used
2. default parameters are parsed only once in the function definition segment.
>>> I = 5 >>> def f (arg = I): >>> print arg >>> I = 6 >>> f () 5 # The result is 5.
When the default value is a variable object, such as a linked list, Dictionary, or most class instances, there are some differences:
>>> Def f (a, L = []): >>> L. append (a) >>> return L >>> print f (1) >>> print f (2) >>> print f (3) [1] [1, 2] [1, 2, 3] # You can use another method: >>> def f (a, L = None): >>> if L is None: >>> L = [] >>> L. append (a) >>> return L
Variable parameters
The parameter is encapsulated into a tuples. Before the variable number parameters, there can be zero to multiple common parameters:
def run(name,*args): print name,'runing' for a in args : print a >>> run('gg','mm') gg runing mm >>> run('gg',1,2,'mm') gg runing 1 2 mm >>> run('gg',1,1.02,['mm','gm']) gg runing 1 1.02 ['mm','gm']
It can be seen that variable parameters can be any multiple and can be of any type (and can be used together)
Variable parameters bound to the keyword (** args is a variable parameter. It is not very understandable to read the original document. It is called this for the time being)
Def run (name, ** args): keys = args. keys () for k in keys: print k, args [k] >>> run ('nana ', type = 'open ') type open >>> run ('nana ', type = 'open', title = 'gogogo ') type open title gogo # * arg must be in front of ** args def run (name, * arg, ** args): for a in arg: print a keys = args. keys () for k in keys: print k, args [k] >>> run ('nn ', 'mm', 1, 2, 'oo', type = 'open ', title = 'gogogo') mm 1 2 oo type open title gogo
Splitting of parameter Columns
>>> range(3, 6) # normal call with separate arguments [3, 4, 5] >>> args = [3, 6] >>> range(*args) # call with arguments unpacked from a list [3, 4, 5]
Lambda keywords allow you to create short anonymous functions.
>>> Def make_incrementor (n):... return lambda x: x + n # is equivalent to creating an anonymous function with x as the parameter? ... >>>> F = make_incrementor (42) # f = make_incrementor (n = 42), set the value of n >>> f (0) # actually calls an anonymous function? 42 >>> f (1) 43 # You can understand the error in the following example >>> def t (n ):... print x * n >>> m = t (2) Traceback (most recent call last): File "<pyshell #85>", line 1, in <module> m = t (2) File "<pyshell #84>", line 2, in t print x * n NameError: global name 'X' is not defined
The global name 'X' is not defined'
>>> x =10 >>> def t(n): ... print x*n >>> m = t(2) 20
I hope this article will help you with Python programming.
How to use functions in the Python Module
1. Know what function (func) you want, in that module, and then import xxx
2. help (xxx. func)
A usage of the print function in python
This can be changed.
List1 = ['dd']
File1 = open('text_file.txt ', 'w ')
File1.write (str (List1 ))
Fiel1.close ()
# Print (List, file = file1)