Python function definition and parameter explanation

Python function definition and parameter explanation#

Function definition##

First, let's create a function to output the Fibonacci series within a specified range.

#! /usr/bin/env python 
# coding=utf-8'''
Created on September 4, 2016 at 2 pm:37:31
@ author: Flowsnow
@ file: D:/Workspaces/eclipse/HelloPython/main/FibonacciSeries.py
@ function:Define function-Output the Fibonacci sequence within a given range
'''
def Fibonacci(n):
 # print "success"
 a=0
 b=1while a<n:
  print a,
  a,b=b,a+b

# call the function Fibonacci
Fibonacci(2000)
print '\n',
print Fibonacci
f=Fibonacci
f(100)
print '\n',
print Fibonacci(0)

The output is as follows:

011235813213455891442333776109871597< function Fibonacci at 0x000000000258D9E8>01123581321345589 
None

It can be seen from the first line that the Fibonacci function outputs a Fibonacci sequence within 2000.
The second line shows the address of the Fibonacci function in memory
From the third line, we can see that after assigning the address value of the Fibonacci function to another variable f, f is a function, which is similar to the duplicate name mechanism
It can be seen from the fourth line that although the Fibonacci function does not have a return statement, if we use print to output, we can find that there is still a return value, but the return value is None, which is the built-in name of Python.

We can also write a function that does not output the value of the Fibonacci sequence, but returns the value as the return value.

#! /usr/bin/env python 
# coding=utf-8'''
Created on September 4, 2016 at 3 pm:07:06
@ author: Flowsnow
@ file: D:/Workspaces/eclipse/HelloPython/main/FibonacciSeriesAdv.py
@ function:Function definition-Return the Fibonacci sequence instead of printing directly
'''
def Fibonacci(n):
 a=0
 b=1
 result=[]while a<n:
  result.append(a)
  a,b=b,a+b
 return result
result=Fibonacci(2000)for x in result:
 print x,

Output result: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

Detailed parameters##

Python’s built-in standard types have a classification standard that is divided into variable types and immutable types

The parameters in the above function definition are all immutable types.

There are three cases of variable parameters: default parameters, positional parameters *args keyword parameters **kwargs.

Default parameters###

The advantage of default parameters is that there are fewer parameters written when calling the function than when the function is defined. E.g:

#! /usr/bin/env python 
# coding=utf-8'''
Created on September 5, 2016 at 2 pm:50:12
@ author: Flowsnow
@ file: D:/Workspaces/eclipse/HelloPython/main/askYesOrNo.py
@ function:Test the use of default parameters
'''
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):while True:
  ok =raw_input(prompt)if ok in('y','ye','yes'):return True
  if ok in('n','no','nop','nope'):return False
  retries = retries -1if retries <0:
   raise IOError('refusenik user')
  print complaint

There are many ways to call this function, such as:

Regarding the default value, it should be noted that the default value will only be parsed by python once when the function is defined. therefore

i =5

def f(arg=i):
 print arg

i =6f()

The output of this code should be 5, not 6, because i is parsed when the function is defined, at this time i=5.

**Important warning: **The default value will only be parsed once. When the default parameter is a variable object, the impact is relatively large, such as a list, dictionary, or class object. The function demonstrated below will accumulate parameters and pass them to subsequent function calls:

def f(a, L=[]):
 L.append(a)return L

print f(1)
print f(2)
print f(3)

This code will output

[1][1,2][1,2,3]

If you don’t want the default parameters to be shared in subsequent function calls, you can write the function in this form

def f(a, L=None):if L is None:
  L =[]
 L.append(a)return L

This code will output

[1][2][3]

Positional parameters *args

Position parameters need to add an asterisk before the parameters. Collect the parameters into a tuple as a variable args. As for why it is called a positional parameter, this is because each parameter is received in order.

def argTest(arg1,*args):
 print arg1
 print('~start to print *args~')for x in args:
  print x,argTest(1,'two',3)

This code will output

1~ start to print *args~
two 3

args is interpreted as a tuple containing multiple variables. So it can also be written as follows:

def argTest(arg1,*args):
 print arg1
 print('~start to print *args~')for x in args:
  print x,

# argTest(1,'two',3)
args=['two',3]argTest(1,*args)

Keyword parameters **kwargs

Functions can also be called with keyword arguments of the form kwarg=value. Keyword parameters need to be prefixed with two asterisks. Its function is to collect the parameters into a dictionary type, including parameter names and values.

def argTest(arg1,**kwargs):
 print 'arg1',arg1
 for key in kwargs:
  print key,kwargs[key]argTest(1,arg2='aa',arg3='bb')argTest(arg1=1,arg2='aa',arg3='bb',arg4='cc')
arg={'arg2':'bb','arg3':'cc','arg4':'dd'}argTest(arg1='ss',**arg)argTest(arg1='ss',**arg)

This code will output

arg1 1
arg2 aa
arg3 bb
arg1 1
arg2 aa
arg3 bb
arg4 cc
arg1 ss
arg2 bb
arg3 cc
arg4 dd
arg1 ss
arg2 bb
arg3 cc
arg4 dd

References##

Python official website-defining-functions

Passing arguments to Python functions1.pdf

The difference between *args and **args in Python

Recommended Posts

Python function definition and parameter explanation
Detailed explanation of the principle of Python function parameter classification
Detailed explanation of -u parameter of python command
Python and Go
Python enumerate() function
Python function buffer
Python introspection and reflection
Python custom function basics
Join function in Python
Python built-in function -compile()
[python] python2 and python3 under ubuntu
Python function basic learning
Python data analysis-apply function
Python3 built-in function table.md
Python deconstruction and packaging
Python3 configuration and entry.md
Python Print print timer function
Python defines a function method
Python automated operation and maintenance 2
Python introduction and environment installation
Python high-order function usage summary!
Python know crawler and anti crawler
Python realizes online translation function
centos7 install python3 and ipython
ubuntu18.04 compile and install python3.8
Centos 6.10 reinstall python and yum
Python open read and write
CentOS7 install python3 and pip3
Python tornado upload file function
Python automated operation and maintenance 1
Python data structure and algorithm
Python magic function eval () learning
Python multi-process and multi-thread basics
How Python implements FTP function
CentOS 6.9 compile and install python
CentOS 6 compile and install python 3
Python method of parameter passing
Generators and iterators in Python
Python implements image stitching function
Python high-order function usage summary!