python解釋器提供了70多個內置函數。
```python
>>> import builtins
>>> print(dir(builtins))
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__IPYTHON__', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'display', 'divmod', 'enumerate', 'eval', 'exec', 'filter', 'float', 'format', 'frozenset', 'get_ipython', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
```
全小寫的就是全局內建函數。
## 基本數據類型函數
### `int`
- int([x]) -> integer
- int(x, base=10) -> integer
講一個數字或者數字字符串轉換成十進制整數,如果x不是一個十進制數字,那么它必須是和進制base匹配的整數字符串表達式
```python
>>> int(1.1)
1
>>> int('1')
1
>>> int('0b0101',2) # 二進制
5
>>> int('0x11',16) # 十六進制
17
>>> int('0o11',8) # 八進制
9
```
### `float`
將一個字符串或數字轉換為浮點數。
```python
>>> float(123)
123.0
>>> float('1.2')
1.2
```
### `complex`
- complex(real=0, imag=0) 創建一個復數通過實部和虛部
```python
>>> complex(10,8)
(10+8j)
```
### `str`
- str(object='') 通過給定的對象創建一個新的字符串對象。
```python
>>> str(1)
'1'
>>> str([1,2,3])
'[1, 2, 3]'
>>> str({'name':'xinlan'})
"{'name': 'xinlan'}"
```
### `list`
- list(iterable=())
根據傳入的可迭代對象創建一個列表,如果沒有參數返回空列表
```python
>>> list()
[]
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list('abcde')
['a', 'b', 'c', 'd', 'e']
```
### `tuple`
- tuple(iterable=())
根據傳入的可迭代對象創建一個元組,如果沒有參數返回空元組
```python
>>> tuple()
()
>>> tuple('abcd')
('a', 'b', 'c', 'd')
```
### `set`
- set(iterable)
根據傳入的可迭代對象創建一個集合對象。
```python
>>> set('abc')
{'a', 'b', 'c'}
>>> set(range(10))
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
```
### `dict`
根據傳入的參數創建一個字典對象
```python
# 形如(key, value)的鍵值對數據
>>> dict([('name','xinlan'),('age',18)])
{'name': 'xinlan', 'age': 18}
# 關鍵字參數
>>> dict(name='xinlan',age=18)
{'name': 'xinlan', 'age': 18}
```
## 常用內建函數
### `print`
- print(value,..,sep=' ', end='\n')
- value 會打印value的字符串形式
- sep 分隔符,當有多個value時默認用空格作為分割
- end 每次打印在最后默認添加回車換行符
打印傳入對象的字符串形式
```python
>>> print(1,2,3,sep=',') # 修改分隔符為,
1,2,3
>>> print(1,end='');print(2) # 修改打印后添加為字符串空
12
```
### `input`
接收用戶的輸入數據,以字符串的形式返回。
可以接收字符串參數最為提示信息輸出
```python
>>> input('>>>:')
>>>:aaa
'aaa'
```
### `type`
- type(object)
返回object的類型
```python
>>> type(1)
int
```
### `dir`
- dir([object])
返回傳入對象的所有屬性和方法名的列表
```python
>>> print(dir(1))
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
```
### `help`
- help(builtins.object)
返回內建對象的幫助信息
```python
>>> help(help)
```
### `len`
- len(obj)
返回容器的元素個數
```python
>>> len([1,2,3])
```
### `hash`
- hash(obj)
返回對象的hash值
```python
>>> hash('a')
3636161774609400683
```
### `iter`
- iter(iterable)
根據傳入的可迭代對象返回一個迭代器
```python
>>> iter('abcd')
<str_iterator at 0x7f98b7dd2eb0>
```
### `id`
- id(obj)
返回傳入對象的身份id(虛擬內存地址的整數形式)
```pyhon
>>> id(1)
4344134656
```
### `range`
- range(stop) -> range object
- range(start, stop[,step])
返回一個range object對象,產生整數序列
```python
>>> range(10)
range(0, 10)
>>> range(0,10,2)
range(0, 10, 2)
```
更多方法詳見[官方文檔](https://docs.python.org/3/library/functions.html)
- 第1章 編程基礎
- 零基礎能學Python嗎?
- 編程語言是什么
- 編譯型與解釋型編程語言的區別
- python是什么?
- 學python能干什么?
- 第2章 python開發環境搭建
- windows下安裝python
- cmd命令行工具
- 環境變量如何設置?
- 如何運行python程序?
- 學習神器Jupyter lab
- 第3章 基本數據類型
- 基本數據類型概述
- 變量的定義和使用
- 整數類型
- 浮點數類型
- 算術運算符
- 賦值運算符
- 字符串類型
- 字符串常用方法
- 字符串格式化
- 列表類型
- 元組類型
- 可變與不可變類型
- 深淺拷貝
- 集合類型
- 字典類型
- 布爾型
- NoneType
- 第4章 程序流程控制
- 程序結構
- if分支語句
- while條件循環
- for循環
- 循環控制關鍵字
- 異常處理
- 第5章函數與代碼復用
- 函數的定義和調用
- 函數的參數
- 函數的返回值
- lambda函數
- 變量作用域
- python內建函數
- 第6章 面向對象
- 類和對象
- 屬性
- 方法
- 繼承
- super()函數
- 多態
- 私有化
- 自省與反射機制
- 第7章 模塊和包
- 模塊
- 包
- 第三方庫
- 第8章 文件IO操作
- 文件概述
- 字符編碼
- 字節類型
- python讀取文件
- python寫文件
- 文件指針