转载请注明出处: http://blog.csdn.net/cxsydjn/article/details/71302965
The note covers funtion syntax, importing modules and build-in functions.
Python notes of open courses @Codecademy.
If you need reuse a piece of code, just with a few different values. Instead of rewriting the whole code, it’s much cleaner to define a function, which can then be used repeatedly.
Function Junction:
Functions are defined with three components:
Header: which includes the def keyword, the name of the function, and any parameters the function requires.Comment: An optional comment that explains what the function does.Body: which describes the procedures the function carries out. The body is indented, just like for conditional statements.
# Example of a function def hello_world(): """Prints 'Hello World!' to the console.""" print "Hello World!"Call and Response:
function(parameters)return sthParameters and Arguments: def square(n): n is a parameter of square. A parameter acts as a variable name for a passed in argument. parameter = formal parameter (形参), argument = actual parameter (实参)。A function can require as many parameters as you’d like, but when you call the function, you should generally pass in a matching number of arguments.Functions Calling Functions A function can call another function, in the way mentioned above.Universal Imports: from module import *
Use the power of from module import * to import everything from the math module.However, they fill your program with a ton of variable and function names without the safety of those names still being associated with the module(s) they came from.
# Examples of the above importing ways # Generic import import math print math.sqrt(25) # Function import from math import sqrt print sqrt(25) # Universal import from math import * print sqrt(25)Tips:
A generic import may be the best way.You may see everything in a module by:
import math # Imports the math module everything = dir(math) # Sets everything to a list of things from math print everything # Prints them all!