python安装、数据类型和变量

2018.06.06
1.1为什么要学习python
学习方法:
边看边做不能只看不做
笔记要记录详细

我们提供的服务有:成都网站建设、成都网站制作、微信公众号开发、网站优化、网站认证、乌拉特后ssl等。为超过千家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的乌拉特后网站制作公司

1.2 python的安装

python是跨平台的语言,linux、windows及mac都可以使用
官网:www.python.org
学习使用的较新版本,使用python3的
windows上的安装过程,安装在C:\Python36目录下,然后点击Install开始安装
python安装、数据类型和变量
在windows中添加python的环境变量,如下:
计算机或我的电脑右击打开属性--系统高级设置
python安装、数据类型和变量
添加python的安装路径,可在用户或系统变量中添加,加入后确认即可
python安装、数据类型和变量
打开windows的CMD,输入python进入python,输入exit()退出
python安装、数据类型和变量
linux中安装python
如果本机安装了python2,尽量不要管他,使用python3运行python脚本就好,因为可能有程序依赖目前的python2环境

比如yum!!!!!教训- -删除了python2安装目录,导致yum不能使用,由于懒得解决,不去修复yum,废了一个虚拟机

  1. 安装依赖环境
    yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel
    sudo yum -y install gcc gcc-c++ 
    sudo yum -y install zlib 
    sudo yum -y install libffi-devel 

    2.下载Python3,官网https://www.python.org/downloads/

3.安装python3

我个人习惯安装在/usr/local/python3(具体安装位置看个人喜好)
创建目录:

mkdir -p /usr/local/python3

解压下载好的Python-3.x.x.tgz包(具体包名因你下载的Python具体版本不不同⽽而不不同,如:我下载的是
Python3.6.1.那我这里就是Python-3.6.1.tgz)

tar -zxvf Python-3.6.1.tgz

4.进入解压后的目录,编译安装。

cd Python-3.6.1
./configure --prefix=/usr/local/python3

编译安装后提示执行./configure --enable-optimizations,执行构建稳定优化的环境

config.status: creating Modules/ld_so_aix
config.status: creating pyconfig.h
creating Modules/Setup
creating Modules/Setup.local
creating Makefile

If you want a release build with all stable optimizations active (PGO, etc),
please run ./configure --enable-optimizations

[root@localhost Python-3.7.0]# ./configure --enable-optimizations
checking build system type... x86_64-pc-linux-gnu
checking host system type... x86_64-pc-linux-gnu
checking for python3.7... no
checking for python3... no
checking for python... python

make之前编译安装pip和ipython
在pypi.python.org官网下载setuptools库和pip
安装setuptools

tar -zxvf setuptools-*.*.tar.gz
cd setuptools-*.*
python3 setup.py build
python3 setup.py install

报错: RuntimeError: Compression requires the (missing) zlib module
  我们需要在linux中安装zlib-devel包,进行支持。
  yum install zlib-devel
  需要对python3.* 进行重新编译安装。
  cd python3.*.1
  make && make install
  又是漫长的编译安装过程。
  重新安装setuptool
  python3 setup.py build
  python3 setup.py install

安装pip的支持扩展

cd pip-*.0.*
python3 setup.py build
python3 setup.py install
如果没有意外的话,pip安装完成。
如果没有搞好环境的话,会碰见亲切的报错:

pip3 install paramiko

报这个错

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
然后开始进行如下操作

yum install openssl
yum install openssl-devel

make install 或者 make && make install 进行最后安装

Looking in links: /tmp/tmptbpyw1pv
Requirement already up-to-date: setuptools in /usr/local/lib/python3.7/site-packages (39.0.1)
Requirement already up-to-date: pip in /usr/local/lib/python3.7/site-packages (10.0.1)

5.建立python3命令的软链接

ln -s /usr/local/python3/bin/python3 /usr/bin/python3

6.并将/usr/local/python3/bin加入PATH

# vim /etc/profile
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
# User specific environment and startup programs
PATH=$PATH:$HOME/bin:/usr/local/python3/bin
export PATH

按ESC,输入:wq回车退出。
修改完记得执行行下面的命令,让上一步的修改生效:

 [root@localhost Python-3.7.0]# source /etc/profile
[root@localhost Python-3.7.0]# python3
Python 3.7.0 (default, Jul  4 2018, 14:06:09) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 
重新读取系统环境配置变量后能够正常使用python3来进入python终端环境了

安装python3.7的pip和ipython工具

升级pip
pip3 install --upgrade pip
安装ipython,可以使用国内源
python3 -m easy_install -i 国内源/simple/地址 ipython

安装系统python2默认ipython命令工具
python支持补全,需要安装ipython的软件包,需要安装python-pip,安装python-pip需要epel扩展
yum install -y epel-release 安装扩展
yum install -y python-pip 安装python-pip

[root@localhost ~]# pip install ipython
Collecting ipython
  Downloading https://files.pythonhosted.org/packages/ee/01/2a85cd07f5a43fa2e86d60001c213647252662d44a0c2e3d69471a058f1b/ipython-6.4.0.tar.gz (5.1MB)
    100% |████████████████████████████████| 5.1MB 101kB/s 
    Complete output from command python setup.py egg_info:

    IPython 6.0+ does not support Python 2.6, 2.7, 3.0, 3.1, or 3.2.
    When using Python 2.7, please install IPython 5.x LTS Long Term Support version.
    Beginning with IPython 6.0, Python 3.3 and above is required.

    See IPython `README.rst` file for more information:

        https://github.com/ipython/ipython/blob/master/README.rst

    Python sys.version_info(major=2, minor=7, micro=5, releaselevel='final', serial=0) detected.
    Your pip version is out of date, please install pip >= 9.0.1. pip 8.1.2 detected.

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-dXTgRG/ipython/
You are using pip version 8.1.2, however version 10.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.安装后提示有新版本可升级
[root@localhost ~]# pip install --upgrade pip       执行pip install --upgrade pip升级pip
Collecting pip
  Downloading https://files.pythonhosted.org/packages/0f/74/ecd13431bcc456ed390b44c8a6e917c1820365cbebcb6a8974d1cd045ab4/pip-10.0.1-py2.py3-none-any.whl (1.3MB)
    100% |████████████████████████████████| 1.3MB 180kB/s 
Installing collected packages: pip
  Found existing installation: pip 8.1.2
    Uninstalling pip-8.1.2:
      Successfully uninstalled pip-8.1.2
Successfully installed pip-10.0.1

安装pip install ipython

安装中报错
[root@localhost ~]# pip install ipython
Collecting ipython
  Using cached https://files.pythonhosted.org/packages/52/19/aadde98d6bde1667d0bf431fb2d22451f880aaa373e0a241c7e7cb5815a0/ipython-5.7.0-py2-none-any.whl
Requirement already satisfied: pygments in /usr/lib64/python2.7/site-packages (from ipython) (2.2.0)
Requirement already satisfied: decorator in /usr/lib/python2.7/site-packages (from ipython) (3.4.0)
Requirement already satisfied: backports.shutil-get-terminal-size; python_version == "2.7" in /usr/lib/python2.7/site-packages (from ipython) (1.0.0)
............
    ----------------------------------------
Command "/usr/bin/python2 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-aBmrn9/scandir/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-hoCRRX/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-install-aBmrn9/scandir/

根据视频使用pip install ipython==3.2.3找到这个版本进行安装

[root@localhost ~]# pip install ipython==3.2.3
Collecting ipython==3.2.3
  Downloading https://files.pythonhosted.org/packages/a8/be/4903b69c5dfb06e4537adbe4b5497048d303258c6d439466a648a0a05be9/ipython-3.2.3-py2-none-any.whl (3.4MB)
    100% |████████████████████████████████| 3.4MB 77kB/s 
Installing collected packages: ipython
Successfully installed ipython-3.2.3
[root@localhost ~]# pip list
Package                            Version
---------------------------------- -------
backports.shutil-get-terminal-size 1.0.0  
backports.ssl-match-hostname      3.5.0.1
configobj                          4.7.2  
decorator                          3.4.0  
enum34                            1.1.6  
iniparse                          0.4    
ipaddress                          1.0.16 
ipython                            3.2.3  
ipython-genutils                  0.2.0  
perf                              0.1    
pip                                10.0.1 
pycurl                            7.19.0 
Pygments                          2.2.0  
pygobject                          3.14.0 
pygpgme                            0.3    
pip list查看安装好的插件

使用ipython进入python环境使用

[root@localhost ~]# ipython
Python 2.7.5 (default, Nov  6 2016, 00:28:07) 
Type "copyright", "credits" or "license" for more information.

IPython 3.2.3 -- An enhanced Interactive Python.
?        -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?  -> Details about 'object', use 'object??' for extra details.

In [1]: print "holle world"    双击tab键补全
holle world

In [2]:exit()
[root@localhost ~]# 

安装这里我也搞的很迷糊,因为第一次安装完使用ipython发现python版本是2.7的,不是我想要的3版本,于是自己动手安装,碰见不少坑文档记录的也不是很全,仅供参考

1.3 python的文件类型

使用方式:一、进入命令行交互模式,二、创建文件,在文件中写入语句
文件中写入:


[root@localhost src]# vim python.py
#!/usr/bin/python     使用python的命令解释器
print 'holle world'
~                                                  
~                                                 
~          
[root@localhost src]# python python.py 
holle world

字节代码,通过compile模块编译后生成的后缀名为pyc的文件

[root@localhost src]# cat 1.py 
#!/usr/bin/python
import py_compile
py_compile.compile('2.py')          2.py是同目录下的另一个文件
[root@localhost src]# python 1.py 
[root@localhost src]# ls
1.py  2.py  2.pyc
cat查看或编辑2.pyc文件,会显示一些乱码,使源码不可见
[root@localhost src]# python 2.pyc 
holle world    
[root@localhost src]# python -O -m py_compile 2.py       字节代码pyo
[root@localhost src]# ls
1.py  2.py  2.pyc  2.pyo
同2.pyc文件一样,cat查看或编辑2.pyo文件,会显示一些乱码,使源码不可见
[root@localhost src]# python 2.pyo
holle world

1.4 python变量

变量是计算机内存中的一个存储数值,变量可以存储规定范围内的值,且值可以改变
python下变量是对一个数据的引用
变量命名规则
以字母、数字、下划线组合
不能以数字开头
不可以使用关键字
变量的赋值
a = 1
id (a) id是查看变量在内存中的地址
python运算符
赋值、算术、关系、逻辑运算符
表达式是将不同数据(包括变量、函数)用运算复航按一定规则连接起来的一种式子
python变量赋值

In [1]: a = 123
In [2]: id(a)
Out[2]: 12392528
In [3]: a = 456
In [4]: id(a)
Out[4]: 22193432
In [5]: x = 'abc'       
In [6]: x = abc         对字符串赋值要使用引号声明,否则会将这个abc识别为一个变量
---------------------------------------------------------------------------
NameError                                Traceback (most recent call last)
 in ()
----> 1 x = abc
NameError: name 'abc' is not defined
In [7]:
type (变量)  查看变量的类型,python会对数值自动归类类型
In [26]: x = 2

In [27]: type (x)
Out[27]: int

In [28]: x = '2'

In [29]: type (x)
Out[29]: str

In [30]:

python赋值运算符

= :   x = 3 , y = 'abcd'
+= :  x += 2
-= :  x -= 2
*= :  x *= 2
/= :  x /= 2
%= :  x %= 2

python算术运算符
+ 加运算 - 减运算 * 乘运算 / 除运算,除数加上小数点可以取得一个精确的浮点结果 // 整除 % 除运算取余
** 运算乘方

In [30]: 3 + 4     加运算
Out[30]: 7

In [31]: 5 - 3     减运算
Out[31]: 2

In [32]: 3 * 4    乘运算
Out[32]: 12 

In [33]: 4 / 3    除运算
Out[33]: 1

In [34]: 4.0 / 3   除运算,除数加上小数点可以取得一个精确的浮点结果
Out[34]: 1.3333333333333333

In [35]: 10 // 3   整除
Out[35]: 3

In [36]: 10 % 3    除运算只取余数
Out[36]: 1

In [37]: 2 ** 3    乘方运算,对结果反复乘以3,这里乘运算了2次,乘公式为:2*2*2   
Out[37]: 8

关系运算符,返回布尔值false 和true结果。true成立,false不成立

大于
< 小于
= 大于或等于
<= 小于或等于
== 等于
!= 不等于


In [38]: 1 > 2    1大于2
Out[38]: False

In [39]: 1 < 2 1小于2
Out[39]: True

In [40]: 1 >= 2 1大于或等于2
Out[40]: False

In [41]: 1 >= 1 1大于或等于1
Out[41]: True

In [42]: 1 <= 2 1小于或等于2
Out[42]: True

In [43]: 1 <= 1 1小于或等于1
Out[43]: True

In [44]: 1 == 1 1等于1
Out[44]: True

In [45]: 1 != 2 1不等于2
Out[45]: True

逻辑运算符
and  逻辑与: true and false    两个表达式都成立返回true,有一个不成立就返回false
or 逻辑或 : false and true     两个表达式只要有一个成立就返回true
not 逻辑非  :  not true      表达式不成立返回true

运算符排列,从下到上优先级越来越高,一行中越往右优先级越高
![](/upload/otherpic64/39c7eb695db492a4ff9634ca58b5c470.png)
从键盘输入读取数值 

input("Please input:")
一个小的计算脚本示例:
[root@localhost src]# cat jisuan.py
#!/usr/bin/python
num1 = input("Please a number: ")
num2 = input("Please a number: ")

print "%s + %s = %s" % (num1, num2, num1+num2)
print "%s - %s = %s" % (num1, num2, num1-num2)
print "%s %s = %s" % (num1, num2, num1num2)
print "%s / %s = %s" % (num1, num2, num1/num2)

[root@localhost src]# python jisuan.py
Please a number: 3
Please a number: 4
3 + 4 = 7
3 - 4 = -1
3 * 4 = 12
3 / 4 = 0

1.5 Python的数值和字串符

python数据类型
数值   字串符   列表   元组  字典
数值类型又分为整型  长整型  浮点型  复数型
整数类型:

In [1]: a = 3
In [2]: type(a)
Out[2]: int
整数类型范围 -2147483648 到 2147483648

长整型:
In [4]: a = 99999999999999999999999999999999999
In [5]: type (a)
Out[5]: long

浮点数类型:
In [6]: 3e+6
Out[6]: 3000000.0
In [7]: type(3e+6)
Out[7]: float
In [8]: 3.0/2
Out[8]: 1.5
In [9]: type(3.0/2)
Out[9]: float

复数类型:
In [10]: a = 34j
In [11]: type(a)
Out[11]: complex

字符串类型,三种引号模式:
a = 'abc'
a = "abc"
a = '''abc'''
三引号有表示注释的意思,也可以代替\n的换行符
In [18]: a = '''holle
....: wrold'''

In [19]: print a
holle
wrold

索引与切片操作,定义a 的变量为123456,操作取出其中某些单独的数字组合
In [20]: a = '123456'

In [21]: a
Out[21]: '123456'

In [22]: a[1] 从0位开始取值,0是数值1,1是数值2,以此类推
Out[22]: '2'

In [23]: a[0]
Out[23]: '1'

In [24]: a[5]
Out[24]: '6'

In [25]: a[0]+a[3]
Out[25]: '14'

In [26]: a[0:4] 整数取值跟字符串有些不同
Out[26]: '1234'

字符串引索
In [27]: b = 'abcde'

In [28]: b [0:2] 字符串引索时0表示开始时的值,引索到结束时的值需要+1,如取出abc两个字符表示[0:3]
Out[28]: 'ab'

In [29]: b [-1] -1表示字符串中最后一个值,这里是e
Out[29]: 'e'

In [30]: b [:3] :表示省去左边的引索匹配,后面跟整数表示取出多少个字符串,不写整数表示取值所有
Out[30]: 'abc'

In [31]: b [1:] :冒号左边跟整数表示省略左边的多少个字符,右边不跟整数表示取出所有,正整数和负整数表达的结果基本一致。如冒号右边的-1和1的取出结果都是bcd
Out[31]: 'bcde'

In [32]: b [1:-1] :冒号左边跟整数表示省略左边的多少个字符,右边不跟负整数表示取出所有,这里负整数倒叙,这里最大取值-1,如果想得出bcde结果,则后面不跟任何数值
Out[32]: 'bcd'

In [36]: b[-4:-2]
Out[36]: 'bc'

In [37]: b[-4:-1]
Out[37]: 'bcd'

In [38]: b[-3:-5:-1] -3从右往左数实际上的第二个,-5从右往左数实际上的第三个,-1表示从右到左的排序 ,倒叙位置 ed[c][b]a
Out[38]: 'cb'

In [52]: b[::2] 双冒号表示步长值,每隔两步取一个值
Out[52]: 'ace'

In [53]: b[::-2] 倒叙的从右往左取值,每隔两步取出一个字符串
Out[53]: 'eca'



整理很乱,基本上都是操作一遍的结果,按操作实践下理解一下其中意思

当前名称:python安装、数据类型和变量
标题来源:http://hbruida.cn/article/jgsege.html