This article takes the numerical calculation as an example to describe the use of functions in Python and share them for reference. Specific as follows:
We all know that the area of the circle is calculated as:
S =ΠR2
When we know the value of radius r, we can calculate the area based on the formula. Suppose we need to calculate the area of 3 circles of different sizes:
R1 = 12.34R2 = 9.08r3 = 73.1S1 = 3.14 * R1 * r1s2 = 3.14 * R2 * r2s3 = 3.14 * R3 * R3
When the code is repeating regularly, you need to be careful, writing 3.14 * x * x is not only troublesome, but if you want to change 3.14 to 3.14159265359, you have to replace it all.
With the function, we no longer write S = 3.14 * x * x every time, but rather write a more meaningful function call S = area_of_circle (x), and the function area_of_circle itself only needs to be written once, it can be called multiple times.
Basically all high-level languages support functions, and Python is no exception. Python is not only very flexible in defining functions, but it has built in many useful functions that can be called directly.
Abstract
Abstraction is a very common concept in mathematics. As an example:
Calculate the sum of the series, for example: 1 + 2 + 3 + ... + 100, it is very inconvenient to write, so mathematicians invented the summation symbol ∑, you can put 1 + 2 + 3 + ... + 100:
100∑nn=1
This abstract notation is very powerful, because we see that ∑ can be understood as sums, rather than reduced to lower-level addition operations.
Moreover, this abstract notation is extensible, such as:
100∑ (n2+1) n=1
The reduction into the addition operation becomes:
(1 x 1 + 1) + (2 x 2 + 1) + (3 x 3 + 1) + ... + (x 100 + 1)
It can be seen that, with the help of abstraction, we do not care about the underlying computational process, but directly consider the problem at a higher level.
The same is true of computer programs, where functions are the most basic form of code abstraction. Flexible use helps to improve programming efficiency.
It is hoped that the examples described in this article will help you with Python programming.