Functions in Python (1)
Friends who have been familiar with C language must be very familiar with the word function. No matter which programming language, functions (of course, in some languages called methods, the meaning is the same) all play a crucial role. Let's take a look at the usage of functions in Python today.
I. Function Definition
In some programming languages, function declarations and function definitions are separated (function declarations and function definitions can appear in different files, such as C languages ), however, in Python, function declarations and function definitions are integrated. In python, the basic form of function definition is as follows:
def function(params): block return expression/value
Here are some notes:
(1) Use the def keyword in Python to define the function. You do not need to specify the type of the returned value.
(2) The function parameter Params can be zero, one, or more. Similarly, the function parameter does not need to specify the parameter type, because in Python, variables are of a weak type, python automatically maintains its type based on the value.
(3) The return statement is optional. It can appear anywhere in the function body, indicating that the execution of the function call has ended. If no return statement exists, none is automatically returned, if there is a return statement, but the return statement is not followed by an expression or a value, none is returned. The following are two examples:
def printHello(): print 'hello' def printNum(): for i in range(0,10): print i return def add(a,b): return a+b print printHello()print printNum()print add(1,2)
Ii. Use of functions
After defining a function, you can use this function. However, in Python, you must note that forward references are not allowed in Python, that is, before defining a function, this function cannot be called. Take a look at the example to understand:
print add(1,2)def add(a,b): return a+b
The result of this program running is:
According to the error message, the function named "add" is not defined. Therefore, to call a function at any time, you must ensure that it is defined before calling.
This article introduces the definition and use of functions. Some complicated concepts and knowledge points of functions will be further explained in function 2 in Python.