Get the App
SLTechnology News&Howtos  ›  Development  › 

How to write and call functions by python

Shulou Source: shulou.com Published: 2022-06-01 13:03:09 10月22日 Update

Most people do not understand the knowledge points of this article "python how to write and call functions", so the editor summarizes the following, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to write python and call functions" article.

Why use functions?

As the project gets bigger and the number of lines of code increases, functions can be used to encapsulate some functions as a module, which makes the code clearer. In addition, encapsulating the repeated code helps to reduce the reuse of the code. Finally, the use of functions can be more convenient for code debugging.

How to write functions in python

Python uses def to define functions. The code structure is as follows:

Def function name (variable 1, variable 2 return...): # define a function using def, which can pass parameters (or no parameters), separated by commas # function internal code variable # you can choose to return a variable or not.

For example:

Def add (a, b): # defines a function named add, and passes in two parameters an and b c = axib # the parameters passed in can be operated. Here a variable c is defined to store the result of the operation return c # returns the value of c using return

How to call a function by python

After you have defined the functions, you can call them directly in the following code. Taking the above add () function as an example, the calling code is as follows:

Def add (a, b): # defines a function named add, and passes in two parameters, an and b c = axib #. The passed parameters can be calculated. A variable c is defined here to store the result of the operation return c # uses return to return the value of c x = 1y = 3add (XMagi y) # directly use the function (usually only functions with no return value will do so) z = add (XMague y) # directly use the function, because the function has a return value, so the formula will assign the return value of the function to zi= add (5Q 6) # all the above example functions pass in variables The value print (add (7)) # can be used in other functions (passing the return result of the function as a parameter to another function). The above is about "how to write and call a function by python". I believe you all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.

Tags: Functions codes parameters variables contents operations results two articles knowledge articles more and more encapsulation selection and then between values functions most of them Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Redmi Shulou Technology Shulou Information vpn