Examples of how to use Python's built in functions

  • 2020-04-02 14:06:39
  • OfStack

This article briefly analyzes the usage of common built-in functions in Python, and shares them with you for your reference. Specific analysis is as follows:

In general, there are many useful functions built into Python that you can call directly.

To call a function, you need to know the name and parameters of the function, such as abs, which takes the absolute value. Can check my document directly from the official website of the Python: http://docs.python.org/2/library/functions.html#abs

You can also view help information for the abs function on the interactive command line through help(abs).

Call abs function:


>>> abs(100)
100
>>> abs(-20)
20
>>> abs(12.34)
12.34

When calling a function, if the number of parameters passed in is not correct, the TypeError will be reported, and Python will explicitly tell you that abs() has and has only one parameter, but gives two:


>>> 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 passed in is correct, but the parameter type cannot be accepted by the function, it will also report a TypeError error and give the error message: STR is the wrong parameter type:


>>> abs('a')
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'

The comparison function CMP (x, y) takes two arguments, if x < Y, return negative 1, if x is equal to y, return 0, if x is equal to y > Y, return 1:


>>> cmp(1, 2)
-1
>>> cmp(2, 1)
1
>>> cmp(3, 3)
0

Data type conversion

Other commonly used functions built into Python include datatype conversion functions, such as the int() function, which converts other datatypes to integers:


>>> int('123')
123
>>> int(12.34)
12
>>> float('12.34')
12.34
>>> str(1.23)
'1.23'
>>> unicode(100)
u'100'
>>> bool(1)
True
>>> bool('')
False

The function name is actually a reference to a function object. You can assign the function name to a variable, which is equivalent to giving the function an "alias" :


>>> a = abs #  variable a Point to the abs function 
>>> a(-1) #  So you can also go through a call abs function 
1

Summary:

To call a Python function, you need to pass in the correct arguments according to the function definition. If the function call is wrong, you must learn to read the error message, so English is very important!

Hopefully, the examples described in this article will be helpful for your Python programming.


Related articles: