python-basic-function

1 Definition and calling of functions

1.1 Function Definition

1.2 Function call

 

2 function parameters

>>> def fun(a, b, *args, **kwargs):
...      """ Variable parameter demonstration example """ 
... print " a = " , a
...     print "b =", b
...     print "args =", args
...     print "kwargs: "
...     for key, value in kwargs.items():
...         print key, "=", value
...
>>> fun( 1 , 2 , 3 , 4 , 5 , m= 6 , n= 7 , p= 8 ) # Note that the passed parameters correspond to
a = 1
b = 2
args = (3, 4, 5)
kwargs:
p = 8
m = 6
n = 7
>>>
>>>
>>>
>>> c = ( 3 , 4 , 5 )
 >>> d = { " m " : 6 , " n " : 7 , " p " : 8 }
 >>> fun( 1 , 2 , *c, ** d) # Note how tuples and dictionaries are passed
a = 1
b = 2
args = (3, 4, 5)
kwargs:
p = 8
m = 6
n = 7
>>>
>>>
>>>
>>> fun( 1 , 2 , c, d) # Note the difference between the above without the asterisk
a = 1
b = 2
args = ((3, 4, 5), {'p': 8, 'm': 6, 'n': 7})
kwargs:
>>>
>>>

 

 

 

3 Function return value

4 Local and global variables

local variable

global variable

Summarize:

  • A variable defined outside a function is called全局变量
  • Global variables can be accessed in all functions
  • If you modify a global variable in a function, you need to use it globalto declare, otherwise an error occurs
  • If the name of the global variable is the same as the name of the local variable, then the local variable is used. Tips强龙不压地头蛇

 

Summary 2:

  • The essence of not modifying global variables when declaring global variables without using global in a function is that the pointing of global variables cannot be modified, that is, global variables cannot be pointed to new data. Lists and dictionaries can be declared without glob
  • For global variables of immutable type, the data pointed to cannot be modified, so global variables cannot be modified without using global.
  • For global variables of variable type, because the data pointed to can be modified, global variables can also be modified when global is not used.

5 Anonymous functions

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325103508&siteId=291194637