实践Python

安装

单独安装pip

1
2
$ sudo apt install python-pip
$ sudo apt install python3-pip

基础

1
2
#!/usr/bin/env python
# -*- coding: utf-8 -*-
1
2
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

区分大小写

变量

动态类型,变量的类型有赋值的数据类型决定,且是可以改变的。

1
2
a = 12
a = '12'

常量一般使用全大写命名

数据类型

整数

浮点数

字符串

布尔值:True和False

空值:None

数据结构

list

1
2
classmates = ['Michael', 'Bob', 'Tracy']
classmates[0]

tuple:不可变

1
classmates = ('Michael', 'Bob', 'Tracy')

函数

print

input

format

ord

chr

encode

decode

len

作用域

一般建议私有变量或函数以”_“开头命名

特殊变量或函数一般命名规则为:__**__

模块

安装第三方模块

1
2
# 安装Pillow模块
$ pip3 install Pillow

引用模块

1
2
import PIL
from PIL import Image

模块搜索路径sys.path

1
2
3
4
5
6
7
8
$ python3
Python 3.6.5 (default, May 11 2018, 13:30:17) 
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/ray/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
>>> 
1
2
3
4
5
6
7
8
$ python2
Python 2.7.15 (default, May  1 2018, 05:55:50) 
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/gtk-2.0']
>>> 

方法一:修改sys.path,当前生效

1
2
>>> import sys
>>> sys.path.append('/Users/michael/my_py_scripts')

方法二:设置环境变量PYTHONPATH,追加到sys.path

参考

Python 3教程

Python 2.7教程