python functions and modules

The role of the functions in Python

To write high-quality code is the first to solve the problem of duplicate code, which may also be an essential operation in most languages.

Defined Functions

Can be used in Python defkeyword to define functions and variables as each function also has a famous name, but naming naming rules are rules and variables are the same. Can be passed in parentheses after the function name placed to function parameters, function and math on this is very similar in function parameters of the program is equivalent to saying the mathematical argument of a function, and the function execution is complete we can by returnto return a key value, which is equivalent to saying that the dependent variable mathematical functions.

Function parameters

Function is a code of the vast majority of programming languages are supported by the "building blocks", but the function of the Python language functions in the other there are still many not the same place, one significant difference is that Python for function parameters deal with. In Python, function parameters can have default values, but also supports the use of variable parameters, so Python does not need to support other languages like overloaded functions , we can make it because there are many different definitions of a function in time use.

With management function module

For any kind of programming language, to variables, functions such identifiers from the names are a vexing problem, because we will encounter this naming conflict awkward situation. The simplest scenario is the definition of the two functions of the same name in the same .py file, since Python has no concept of function overloading, then before the latter definition will cover the definition, it means that the two functions are actually a function of the same name only one is present.

example:

And function calculating achieve greatest common divisor of the least common multiple.

def gcd(x, y):
(x, y) = (y, x) if x > y else (x, y)
for factor in range(x, 0, -1):
if x % factor == 0 and y % factor == 0:
return factor

def lcm(x, y):
return x * y // gcd(x, y)

 

Guess you like

Origin www.cnblogs.com/wangshilin/p/11297693.html