设为首页 加入收藏

TOP

Python---基础知识、数值类型、字符串
2019-03-19 14:33:37 】 浏览:46
Tags:Python--- 基础知识 数值 类型 字符串
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/WY_mini/article/details/73865729
一、python背景介绍

1.python含义
python是一种解释型的、面向对象的、带有动态语义的高级程序设计语言

2.python的版本特性
python2.7最新,2版本后续将不再开发
python3推出 与2特性一样,但是版本代码不兼容
python2.6是一个过渡版本,既可以执行,又包含python3.0的新特性
现在企业实战应用python版本为2.7版本

3.python的优点
*创始人评价:简单、优雅、明确
~简单体现在如果你的母语是英语,写python脚本就像写文章,很简单;
~优雅体现在python的格式,比如缩进来确定代码块,可避免编程人员进行复杂的嵌套;
~明确体现在解决问题的方法只有一种最优选项,而perl语言是每个问题有很多最优解,但不利于团队协作;
*有强大的第三方库模块,需要实现一复杂功能,只需要调用现有的库,可快速实现功能。20多年的发展,各种库都已经完备,比如:邮件库,爬虫库......
*可跨平台移植,java有Java的虚拟机,python同样;
*是一种面向对象的语言;
*是一种可扩展的语言(与C,C++,Java结合)

4.python的缺点
*python(解释型)代码执行速度慢,相比C语言(描述型,编译型),不过现在python的异步并发框架导致执行速度慢;
*python是开源的编程语言,代码不能加密,当然有相应的工具可以将python代码转换为exe的二进制可执行码,但是反解码也很容易;

5.python的应用
*软件开发:游戏后台、搜索、图形界面
网站
科学运算
*系统管理:脚本
IT自动化工具

二、python环境配置

1.安装
在配置好yum源的情况下执行

yum install python -y



2.查看python版本
[root@desktop31 ~]# python -V
Python 2.7.5
[root@desktop31 ~]# python --version
Python 2.7.5



3.进入python交互界面
[root@desktop31 ~]# python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hello world!" ##输出hello world!
hello world!
>>> exit() ##退出,也可以安CTRL+D



4.定义变量
### 临时定义 (存放在内存)###
交互式环境中执行动作
[root@desktop31 ~]# python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 1 ##定义变量
>>> print a ##显示变量
1
>>> exit() ##退出

[root@desktop31 ~]# python ##再次进入
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined ##报错:变量a未定义,上次交互界面定义的变量值是没有被保存的
>>> exit()


### 永久定义(存放在硬盘)###

脚本的方式执行动作
[root@desktop31 mnt]# vim hello.py
#!/usr/bin/python ##指定脚本解释器
a = 1
print a
[root@desktop31 mnt]# chmod +x hello.py
[root@desktop31 mnt]# ./hello.py

1



#!/usr/bin/python 这种写法表示直接引用系统的默认的 Python 版本,这样的话 python 程序移植到其他机器上可能运行的时候有问题,因为别人系统默认的 Python 版本与你预期的并不一致

当我们在拥有不同版本python中执行python时下面这样定义解释器可以解决版本问题
[root@desktop31 mnt]# vim hello.py
#!/usr/bin/env python ##引用环境变量里面自定义的 Python 版本,具有较强的可移植性
a = 1
print a
[root@desktop31 mnt]# chmod +x hello.py
[root@desktop31 mnt]# ./hello.py
1



三、python编码

1.字符问题
[root@desktop31 mnt]# vim hello.py
#!/usr/bin/env python
a = "你好" ##当脚本中出现中文时是无法执行的
print a
[root@desktop31 mnt]# chmod +x hello.py
[root@desktop31 mnt]# ./hello.py ##脚本执行报错
File "./hello.py", line 2
SyntaxError: Non-ASCII character '\xe4' in file ./hello.py on line 2, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details


vim hello.py

#!/usr/bin/env python
#coding:utf-8 ##指定编码,以下方式任选一
#coding=utf-8
#encoding:utf-8
#encoding=utf-8
a = "你好"
print a
[root@desktop31 mnt]# ./hello.py
你好


2.字符编码
ASCII:用二进制存储数据,英文字母加各个字符一共128个,1字节=8位,2^8=256,可通过ord()函数去查看字符对应的ASCII码,ASCII码忽略了中文,韩文,日文等其他国家的文字,256个字符的对应关系明显是不够用的
Unicode:中文出现 2字节=16 2^16=65536 ,a--> 2byte 中文 你-->2byte
UTF-8:可变长度编码格式,如果英文 a-->1byte,中文 你--->3byte
GB2312:2字节

3.字符的编码与解码
当存储数据到硬盘,需要考虑到节省空间的问题,所以采用utf-8格式进行存储
当将数据读入内存时,统一一个编码格式便于操作,采用unicode编码格式

字符编码(encode):Unicod --> utf-8
字符解码(decode):utf-8 --> Unicod

1)指定字符编码
[root@desktop31 mnt]# python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = '你好'
>>> type(a) ##查看字符类型
<type 'str'> ##字符串(utf-8)
>>> a = u'你好' ##定义a的字符串为unicode
>>> type(a)
<type 'unicode'>
>>> exit()


2)编码与解码

[root@desktop31 mnt]# python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> name_unicode = u'中国' ##定义变量为unicode,内存中存储方便
>>> type(name_unicode) ##查看字符类型
<type 'unicode'>
>>> print name_unicode
中国
>>> name_utf8 = name_unicode.encode('utf-8') ##在存储到硬盘时需要编码为utf8为节省磁盘空间
>>> type(name_utf8)
<type 'str'>
>>> print name_utf8
中国
>>> name_unicode1 = name_utf8.decode('utf-8') ##从磁盘中调出代码需要解码成Unicode到内存中调用
>>> type(name_unicode1)
<type 'unicode'>
>>> print name_unicode1
中国
>>> exit()


四、辅助工具

1.python解释器种类
cpython
ipython:cpython高配,交互方式有所增强
Jpython:java平台上的python解释器,将python代码编译成java字节码执行
IronPython:直接将python代码编译成.net的字节码
PYPY:对代码进行动态编译,JIT技术(just-in-time compiler,即时编译器),显著提高代码执行速度

2.ipython
1)安装
[root@desktop31 ~]# cd /ipython/
[root@desktop31 ipython]# ls
openpgm-5.2.122-2.el7.x86_64.rpm
python-ipython-3.2.1-1.el7.noarch.rpm
python-ipython-console-3.2.1-1.el7.noarch.rpm
python-ipython-gui-3.2.1-1.el7.noarch.rpm
python-jsonschema-2.3.0-1.el7.noarch.rpm
python-mistune-0.5.1-1.el7.x86_64.rpm
python-path-5.2-1.el7.noarch.rpm
python-pip-7.1.0-1.el7.noarch.rpm
python-pygments-1.4-9.el7.noarch.rpm
python-simplegeneric-0.8-7.el7.noarch.rpm
python-zmq-14.3.1-1.el7.x86_64.rpm
zeromq3-3.2.5-1.el7.x86_64.rpm

[root@desktop31 ipython]# yum install * -y ##安装


2)使用
[root@desktop31 ~]# ipython ##进入ipython
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
Type "copyright", "credits" or "license" for more information.

IPython 3.2.1 -- 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]: name_unicode = u'中国' ##输入命令

In [2]: type(name_unicode)
Out[2]: unicode

In [3]: print name_unicode
中国

In [4]: exit() ##退出


3.pycharm
1)安装
[root@desktop31 Desktop]# ls
pycharm-community-2017.1.4.tar.gz
[root@desktop31 Desktop]# tar zxf pycharm-community-2017.1.4.tar.gz
[root@desktop31 Desktop]# ls
pycharm-community-2017.1.4 pycharm-community-2017.1.4.tar.gz
[root@desktop31 Desktop]# cd pycharm-community-2017.1.4/
[root@desktop31 pycharm-community-2017.1.4]# ls
bin help Install-Linux-tar.txt lib plugins
build.txt helpers jre64 license
[root@desktop31 pycharm-community-2017.1.4]# cd bin/
[root@desktop31 bin]# ls
format.sh idea.properties pycharm64.vmoptions restart.py
fsnotifier inspect.sh pycharm.png
fsnotifier64 log.xml pycharm.sh
fsnotifier-arm printenv.py pycharm.vmoptions

[root@desktop31 bin]# sh pycharm.sh ##进入pycharm


2)配置

#添加文件头
#!/usr/bin/env python
#coding:utf-8
_author_ = "wangying"
'''
@author:wangying
@file:${NAME}.py
@contact:1172420437@qq.com
@DATE:${DATE}${TIME}
@desc
'''




五、python的编程代码风格
1.C的代码风格
#include <stdio.h>
void hello()
{
printf("hello!\n");
}
void main()
{
hello();
}


我们可以看到,在C中写代码缩进是不做要求的,并且C代码块是通过花括号 {} 做以区别


2.python编码风格
总结python编程初级要掌握的编程风格如下:
*不要在行尾加分号;
*每行不超过80个字符;
*Python语言利用缩进表示语句块的开始和退出(Off-side规则),而非使用花括号或者某种关键字。
*增加缩进表示语句块的开始,而减少缩进则表示语句块的退出。缩进成为了语法的一部分。

##代码一使用了正确缩进格式
#!/usr/bin/env python
def hello(): ##def定义函数
print "hello!"
def main():
hello()
print "word!"
main()

[root@desktop31 mnt]# python hello.py
hello!
word!


##代码二缩进格式不正确

#!/usr/bin/env python
def hello():
print "hello"
def main():
hello()
print "world" ##此行应该缩进但是没有
main()

[root@desktop31 mnt]# python hello.py
word! ##先执行了print "world",main中没有包含到
hello!



3.python注释

*单行注释: #常被用作单行注释符号,#开头的行,其右边的任何数据都会被忽略,当做是注释。
*块注释: 需要批量文本或代码时,使用三引号 ''' '''.,当然三引号也可以实现多行文本格式化打印
##脚本示例:
#示例一
#!/usr/bin/env python
print "hello!"
print "word!"

[root@desktop31 mnt]# python hello.py
hello!
word!


#示例二

#!/usr/bin/env python
#print "hello!"
print "word!"

[root@desktop31 mnt]# python hello.py
word!


#示例三

#!/usr/bin/env python
''' ##注释整段
print "hello!"
print "word!"
'''

[root@desktop31 mnt]# python hello.py ##没有任何输出



4.输入

[root@desktop31 mnt]# python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> name = raw_input('Name:') ##raw_input写入的内容赋值给变量name,输入的内容为字符类型
Name:wy
>>> print name
wy
>>> age = raw_input('Age:') ##用raw_input赋值给age
Age:6
>>> print age
6
>>> print age>1
True
>>> print age>10 ##判断出错
True
>>> age = input('Age:') ##input写入的内容赋值给变量age,输入的内容为数值类型
Age:6
>>> print age
6
>>> print age>10
False
>>> exit()


#### pycharm示例 ####

1.编写-python文件,定义变量x=10,通过if语句判断,
如果x>0,输出"x是正数",并输出x-10的值;
如果x<0,输出"x是负数",并输出x+10的值;
如果x=0,输出"x为零"
#!/usr/bin/env python
#coding:utf-8
_author_ = "wangying"
'''
@author:wangying
@file:hello.py
@contact:1172420437@qq.com
@time:6/28/1710:15 AM
@desc
'''
x = 10
if x>0:
print 'x是正数'
print x-10
elif x<0:
print "x负数"
print x+10
else:
print "x为零"

2.编写一程序,录入信息包括 hostname、IP、used_year、CPU、Memory、manager_name ,如果使用年限超过10年,直接显示警告信息“该服务器使用年限太久!”,如果使用年限不超过10年,显示该服务器信息如下面的格式如下:


#!/usr/bin/env python

#coding:utf-8
_author_ = "wangying"
'''
@author:wangying
@file:hello.py
@contact:1172420437@qq.com
@time:6/28/1710:15 AM
@desc
'''
hostname = raw_input('主机名: ') ##raw_input定义字符变量
IP = raw_input('IP: ')
used_year = input('used_year: ') ##input定义数字变量
CPU = raw_input('CPU: ')
Memory = raw_input('Memory: ')
manager_name = raw_input('manager_name: ')
if used_year < 10:
a = ''' ##'''指定格式输出
主机信息
主机名 :%s ##%s为字符占位符号
IP :%s
使用年限 :%d ##%d为数字占位符号
CPU :%s
Memory :%s
manager_name:%s
''' %(hostname, IP, used_year, CPU, Memory,manager_name) ##让占位符号取值
print a
else:
print '该服务器使用年限太久!'



六、python变量的定义

变量是内存中的一块区域。
变量的命名: 变量名由字母,数字,下划线组成。

[root@desktop31 mnt]# python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 1
>>> print a
1
>>> a_1 = 2
>>> print a_1
2
>>> _a = 3
>>> print _a
3
>>> 1a = 4
File "<stdin>", line 1
1a = 4
^
SyntaxError: invalid syntax
>>> a-1 = 5
File "<stdin>", line 1
SyntaxError: can't assign to operator
>>> exit()


python中地址变量与c语言刚好相反,一条数据包含包含多个标签;

[root@desktop31 mnt]# python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 1
>>> b = 1
>>> id(a)
34258024
>>> id(b)
34258024
>>> exit()


## 简要描述Python的垃圾回收机制(garbage collection) ##

Python在内存中存储了每个对象的引用计数(reference count)。如果计数值变成0,那么相应的对象就会消失,分配给该对象的内存就会释放出来用作他用。
PyObject是每个对象必有的内容,其中ob_refcnt就是做为引用计数。当一个对象有新的引用时,它的ob_refcnt就会增加,当引用它的对象被删除,它的ob_refcnt就会减少.引用计数为0时,该对象生命就结束了。


七、python运算符
1.赋值运算符:=、+=、-=、/=、%=、*=、**=、
[root@desktop31 mnt]# python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 10
>>> print a
10
>>> a += 1
>>> print a
11
>>> a -= 1
>>> print a
10
>>> a /= 2
>>> print a
5
>>> a *= 3
>>> print a
15
>>> a %= 2
>>> print a
1
>>> exit()


2.算术运算:+、-、*、/、//、%、**

[root@desktop31 mnt]# python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 + 1
2
>>> 1 - 1
0
>>> 2 * 3
6
>>> 1 / 2
0
>>> 1.0 / 2
0.5
>>> 1.0 // 2
0.0
>>> 1 % 2
1
>>> 2 ** 3
8
>>> exit()


3.关系运算(返回一个布尔类型的结果):<、>、>=、<=、==、!=

[root@desktop31 mnt]# python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 < 2
True
>>> 1 > 2
False
>>> 2 >= 2
True
>>> 2 <= 2
True
>>> 2 == 2
True
>>> 2 != 2
False
>>> 3 != 2
True
>>> exit()


4.逻辑运算:and #逻辑与

or #逻辑或
not #逻辑非
1 #本身代表true
0 #代表False
[root@desktop31 mnt]# python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 2>1 and 3>2
True
>>> 2>1 and 1>2
False
>>> 2>1 or 1>2
True
>>> 0>1 or 1>2
False
>>> not 1>2
True
>>> not 1
False
>>> not 0
True
>>> exit()


示例:

编写一个四则运算
#!/usr/bin/env python
#coding:utf-8
from __future__ import division ##导入python未来支持的语言特征division(精确除法)
_author_ = "wangying"
'''
@author:wangying
@file:hello.py
@contact:1172420437@qq.com
@time:6/28/1710:15 AM
@desc
'''
NUM1 = input('Please input first num: ')
NUM2 = input('please input secend num: ')
ACTION = raw_input('please input acton: ')
if ACTION == '+':
print NUM1 + NUM2
elif ACTION == '-':
print NUM1 - NUM2
elif ACTION == '*':
print NUM1 * NUM2
elif ACTION == '/':
print NUM1 / NUM2
else:
print '请在动作提示后输入:+|-|*|/'



八、基本数据类型

1.数字
整形 int
长整形 long
强制定义为长整型 num2 = 1L
浮点型(小数) float
[root@desktop31 mnt]# python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> num1 = 1
>>> type(num1)
<type 'int'>
>>> num1 = 11111111111111111111111111111111111111
>>> type(num1)
<type 'long'>
>>> num2 = 1L
>>> type(num2)
<type 'long'>
>>> num3 = 1.2
>>> type(num3)
<type 'float'>
>>> exit()


2.字符串

1)字符串定义:' '、" "、""" """
[root@desktop31 mnt]# python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'hello world'
>>> print a
hello world
>>> b = "hello world"
>>> print b
hello world
>>> c = """hello world"""
>>> print c
hello world
>>> type(a)
<type 'str'>
>>> type(b)
<type 'str'>
>>> type(c)
<type 'str'>
>>> exit()


### 注意:''不能识别' ###

[root@desktop31 mnt]# python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> say = 'let's go'
File "<stdin>", line 1
say = 'let's go'
^
SyntaxError: invalid syntax
>>> say = "let's go"
>>> print say
let's go
>>> exit()

2)转义符号
tab \t
换行 \n
[root@desktop31 mnt]# python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> mail = 'tom: hello i am happy'
>>> print mail
tom: hello i am happy
>>> mail = 'tom:\t hello\t i am happy'
>>> print mail
tom: hello i am happy
>>> mail = 'tom:\n hello\n i am happy'
>>> print mail
tom:
hello
i am happy
>>> exit()

3)三重引号

块注释
函数的doc文档
字符串格式化
[root@desktop31 mnt]# python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> mail = """tom:
... hello
... i am happy
... """
>>> print mail
tom:
hello
i am happy

>>> mail
'tom:\n\thello\n\ti am happy\n'
>>> exit()

4)字符串索引
[root@desktop31 mnt]# python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'hello world'
>>> a[0]
'h'
>>> a[1]
'e'
>>> a[-1]
'd'
>>> a[1]+a[6]
'ew'
>>> exit()

5)字符串切片
a[从那里:到那里:步长]
[root@desktop31 mnt]# python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'hello world'
>>> a[1:5] ##代表切片取出第2个到第4个
'ello'
>>> a[:5] ##代表切片取出第4个之前的
'hello'
>>> a[5:] ##代表切片取出第4个之后的
' world'
>>> a[5:1] ##python中默认是从左向右取值
''
>>> a[:] ##代表切片取出所有
'hello world'
>>> a[-4:-1] ##代表倒数第4个到倒数第2个切片
'orl'
>>> a[1:5:2] ##代表切片从第2个到第4个隔两个取一个
'el'
>>> a[-2:-4:-1] ##代表从倒数第4个到倒数第2个隔一个取一个
'lr'
>>> a[5:1:-2] ##当步长为-1时,从右向左取值
' l'

>>> exit()



】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python第八天 模块   包 &n.. 下一篇linux环境下安装python

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目