We know that the formula for calculating the area of a circle is:
When we know the value of the radius r, we can calculate the area using this formula. Suppose we need to calculate the areas of three circles of different sizes:
r1 = 12.34
r2 = 9.08
r3 = 73.1
s1 = 3.14 * r1 * r1
s2 = 3.14 * r2 * r2
s3 = 3.14 * r3 * r3
You need to be cautious when your code contains regular repetitions. Writing 3.14×x×x every time is not only cumbersome, but also if you want to change 3.14 to 3.14159265359, you have to replace it everywhere.
With functions, instead of writing s=3.14×x×x every time, we can use a more meaningful function call: s=area_of_circle(x). The function area_of_circle itself only needs to be written once and can be called multiple times.
Virtually all high-level programming languages support functions, and Python is no exception. Python not only allows flexible function definition, but also has many useful built-in functions that can be called directly.
Abstraction is a very common concept in mathematics. Here is an example:
Calculating the sum of a sequence, such as 1+2+3+…+100, is very inconvenient to write out in full. Therefore, mathematicians invented the summation symbol ∑, which allows us to write 1+2+3+…+100 as:
This abstract notation is extremely powerful, because when we see ∑, we immediately understand it represents summation, rather than reverting to the low-level addition operation.
Moreover, this abstract notation is extensible. For example:
When expanded into an addition operation, it becomes:
(1×1+1)+(2×2+1)+(3×3+1)+…+(100×100+1)
It is evident that with the help of abstraction, we can ignore the underlying specific calculation process and directly think about problems at a higher level.
The same principle applies to writing computer programs: functions are the most fundamental way of code abstraction.