Python has many useful built-in functions that we can call directly.
To call a function, you need to know its name and parameters. For example, the function abs() calculates the absolute value and takes exactly one argument. You can check the documentation on Python’s official website or use help(abs) in the interactive command line to view help information for the abs() function.
Calling the abs() function:
>>> abs(100)
100
>>> abs(-20)
20
>>> abs(12.34)
12.34
When calling a function, if the number of arguments passed is incorrect, a TypeError will be raised, and Python will clearly inform you: abs() takes exactly one argument, but two were given.
>>> 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 arguments is correct, but the type of the argument cannot be accepted by the function, a TypeError will also be raised with an error message indicating that str is the wrong argument type.
>>> abs('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'
The max() function, however, can take any number of arguments and returns the largest one:
>>> max(1, 2)
2
>>> max(2, 3, 1, -5)
3
Commonly used built-in Python functions also include data type conversion functions. For example, the int() function can convert other data types to integers:
>>> 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
A function name is actually a reference that points to a function object. You can completely assign a function name to a variable, which is equivalent to giving the function an “alias”:
>>> a = abs # The variable a points to the abs function
>>> a(-1) # Therefore, you can also call the abs function through a
1
To call a Python function, you need to pass the correct arguments according to the function definition. If a function call results in an error, it is essential to learn how to read the error message. Therefore, knowledge of English is very important!