Function
Definition of a function keyword: def
Using the global statement makes it clear that the variable is defined outside the block
Example: (The value of X is 2 after the function has finished running)
#!/usr/bin/python# Filename: func_global.pydef func(): global x print ‘x is‘, x x = 2 print ‘Changed local x to‘, xx = 50func()print ‘Value of x is‘, x
You can give the shape a default value, the default parameter is immutable, and only those parameters at the end of the formal parameter list can have default parameter values, that is, you cannot declare a function parameter, declare a parameter with a default value, and then declare that there is no default
The formal parameter of the value. This is because the value assigned to the parameter is assigned according to the position. For example, Def func (A, b=5) is valid, but def func (a=5, b) is not valid.
Example:
#!/usr/bin/python# Filename: func_default.pydef say(message, times = 1): print message * timessay(‘Hello‘)say(‘World‘, 5)
HelloWorldWorldWorldWorldWorld
#!/usr/bin/python# Filename: func_key.pydef func(a, b=5, c=10): print ‘a is‘, a, ‘and b is‘, b, ‘and c is‘, cfunc(3, 7)func(25, c=24)func(c=50, a=100)
Operation Result:
$ python func_key.pya is 3 and b is 7 and c is 10a is 25 and b is 5 and c is 24a is 100 and b is 5 and c is 50
The pass statement represents an empty block of statements in Python. Like in the java/c++;
Unless you provide your own return statement, each function contains a return none statement at the end
Document String docstrings, all it does is grab the __doc__ property of the function and show it to you neatly.
#!/usr/bin/python# Filename: func_doc.pydef printMax(x, y): ‘‘‘Prints the maximum of two numbers. The two values must be integers.‘‘‘ x = int(x) # convert to integers, if possible y = int(y) if x > y: print x, ‘is maximum‘ else: print y, ‘is maximum‘printMax(3, 5)print printMax.__doc__
Python Learning Path-the third day-function