Python function (1) What is a function

silencement
Release: 2019-07-08 10:23:39
Original
3073 people have browsed it

Python function (1) What is a function

Friends who have been exposed to the C language must be very familiar with the word function. No matter which programming language it is in, a function (of course it is called a method in some languages) has the same meaning. ) all play a vital role. Today let’s learn about function usage in Python.

1. Function definition

In some programming languages, function declarations and function definitions are separated (in these programming languages, function declarations and function definitions can appear in different files (such as C language), but in Python, function declaration and function definition are regarded as one. In Python, the basic form of function definition is as follows:

def function(params):
    block    
    return expression/value
Copy after login

Here are a few points:

(1) Use the def keyword in Python to define a function without specifying a return value type.

(2) Function parameter params can be zero, one or more. Similarly, function parameters do not need to specify parameter types, because variables in Python are weakly typed, and Python will automatically Maintain its type.

(3) The return statement is optional. It can appear anywhere in the function body, indicating that the function call execution ends here; if there is no return statement, NONE will be automatically returned. If there is a return statement, but return If there is no expression or value after it, NONE will be returned.

Look at two examples below:

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)
Copy after login

The above is the detailed content of Python function (1) What is a function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template