Appearance
Calling Functions
We know that the formula for calculating the area of a circle is:
S = πr²
When we know the value of the radius ( r ), we can calculate the area based on this formula. Suppose we need to calculate the area of three circles with different sizes:
python
r1 = 12.34
r2 = 9.08
r3 = 73.1
s1 = 3.14 * r1 * r1
s2 = 3.14 * r2 * r2
s3 = 3.14 * r3 * r3
When the code shows a regular repetition, you need to be cautious. Writing 3.14 * x * x
each time is not only cumbersome, but if you want to change 3.14
to 3.14159265359
, you will have to replace it everywhere.
With functions, we no longer need to write s = 3.14 * x * x
every time, but instead, we can write 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.
Basically, all high-level languages support functions, and Python is no exception. Python can not only define functions very flexibly but also comes with many useful built-in functions that can be called directly.
Calling the abs Function
python
>>> abs(100)
100
>>> abs(-20)
20
>>> abs(12.34)
12.34
When calling a function, if the number of parameters passed is incorrect, a TypeError
will occur, and Python will explicitly tell you: abs()
takes exactly one argument (1 given):
python
>>> abs(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: abs() takes exactly one argument (2 given)
If the number of parameters is correct but the parameter type cannot be accepted by the function, a TypeError
will also occur, giving an error message that str
is the wrong parameter type:
python
>>> abs('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'
The max
function max()
can accept any number of parameters and return the largest one:
python
>>> max(1, 2)
2
>>> max(2, 3, 1, -5)
3
Data Type Conversion
Python's built-in common functions also include data type conversion functions. For example, the int()
function can convert other data types to integers:
python
>>> int('123')
123
>>> int(12.34)
12
>>> float('12.34')
12.34
>>> str(1.23)
'1.23'
>>> str(100)
'100'
>>> bool(1)
True
>>> bool('')
False
The function name is actually a reference pointing to a function object, and you can assign the function name to a variable, which is equivalent to giving this function an "alias":
python
>>> a = abs # variable a points to the abs function
>>> a(-1) # so you can also call the abs function through a
1
Exercise
Please use Python's built-in hex()
function to convert an integer to a hexadecimal string:
python
n1 = 255
n2 = 1000
print(???)
Summary
To call a Python function, you need to pass the correct parameters according to the function definition. If a function call fails, it is essential to learn to read the error messages, so knowing English is very important!