Python基础1

###########################
## 简述python的垃圾回收机制 ##
###########################


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


1. 名称定义
垃圾(Garbage):垃圾就是你们不能被引用也不能被访问的对象。
     比如某个对象是有一个名字与它连接并引用的,突然在某个时候,那个名字就去引用其他对象了,那么这个对象就被孤立了,也就是说再也没有其他名字去引用它了,那么我们就称这个对象是垃圾。


2.引用计数
引用计数法在对象内部维护了一个被其他对象引用数的引用计数值,当这个引用计数值为0时,说明这个对象不再被其他对象引用,就可以被回收了。


优点:
    高效
    运行期没有停顿
    对象有确定的生命周期
    易于实现
缺点:
    维护引用计数的次数和引用赋值成正比,而不像mark and sweep等基本与回收的内存数量有关。
    无法解决循环引用的问题。A和B相互引用而再没有外部引用A与B中的任何一个,它们的引用计数都为1,但显然应该被回收。


为了解决这两个致命弱点,Python又引入了以下两种GC机制。


3. 标记-清除
“标记-清除”法是为了解决循环引用问题。可以包含其他对象引用的容器对象(如list, dict, set,甚至class)都可能产生循环引用,为此,在申请内存时,所有容器对象的头部又加上了PyGC_Head来实现“标记-清除”机制。在为对象申请内存的时候,可以明显看到,实际申请的内存数量已经加上了PyGC_Head的大小。


4. 分代回收
分代回收的整体思想是:将系统中的所有内存块根据其存活时间划分为不同的集合,每个集合就成为一个“代”,垃圾收集频率随着“代”的存活时间的增大而减小,存活时间通常利用经过几次垃圾回收来度量。Python默认定义了三代对象集合,索引数越大,对象存活时间越长。新生成的对象会被加入第0代,前面_PyObject_GC_Malloc中省略的部分就是Python GC触发的时机。每新生成一个对象都会检查第0代有没有满,如果满了就开始着手进行垃圾回收。




##################
## ipython的安装 ##
##################


[root@foundation44 pack]# cd /home/kiosk/Desktop/资料包/
ipython/ RH134/   RH254/   
[root@foundation44 pack]# cd /home/kiosk/Desktop/资料包/ipython/
[root@foundation44 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@foundation44 ipython]# yum install * -y


##################
## pycharm的安装 ##
##################


[root@foundation44 ipython]# cd /home/kiosk/Desktop/资料包/
[root@foundation44 资料包]# ls
dovicot                                 RH254
ipython                                 RHCSA-EXAM.pdf
iscsi                                   thunderbird-31.2.0-1.el7.x86_64.rpm
phpMyAdmin-3.4.0-all-languages.tar.bz2  实验四shell编程.wps
pycharm-community-2017.1.4.tar.gz       访问网络文件共享服务
RH134
[root@foundation44 资料包]# tar zxf pycharm-community-2017.1.4.tar.gz 
[root@foundation44 资料包]# cd pycharm-community-2017.1.4/
[root@foundation44 pycharm-community-2017.1.4]# ls
bin        help     Install-Linux-tar.txt  lib      plugins
build.txt  helpers  jre64                  license
[root@foundation44 pycharm-community-2017.1.4]# cd bin
[root@foundation44 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@foundation44 bin]# ./pycharm.sh 








###########
## 知识点 ##
###########


1.用python写的:
Youtube  Google NASA
豆瓣网  tragetcli  Saltstack


2.Python的优点
(1)有很多优秀的第三方库:shell C Java 邮件库 爬虫库
(2)便于开发
(3)移植性强,可跨平台移植
(4)是一种可扩展的语言(与C,C++,Java结合)


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


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


5.python的安装
(1)访问python官网,下载不同平台下的python软件;
(2)Linux操作系统上一般iso镜像里面自带,直接通过yum安装;
注意点:
(1)python2.6是一个过渡版本,既可以执行,又包含python3.0的新特性;
(2)现在企业实战应用python版本为2.7版本;
(3)python2.7是python2.x系列最后一个版本,不会再有python3.0;




6.Python的交互式环境的退出
(1)exit()
(2)ctrl+d
-----------------------------------------------------------
[kiosk@foundation44 Desktop]$ python
Python 2.7.5 (default, Oct 11 2015, 17:47:16) 
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hello!!"
hello!!
>>> exit()
[kiosk@foundation44 Desktop]$ python
Python 2.7.5 (default, Oct 11 2015, 17:47:16) 
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 
[kiosk@foundation44 Desktop]$ 
------------------------------------------------------------


7.在shell中对变量的赋值退出此python就不存在了
------------------------------------------------------------
[kiosk@foundation44 Desktop]$ python
Python 2.7.5 (default, Oct 11 2015, 17:47:16) 
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a=1
>>> print a
1
>>> 
[kiosk@foundation44 Desktop]$ python
Python 2.7.5 (default, Oct 11 2015, 17:47:16) 
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] 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
>>> 
-----------------------------------------------




8.python脚本的执行
(1)python filename.py
(2)chmod +x filename.py
   ./filname.py
-----------------------------------------------
[root@foundation44 mnt]# vim hello.py
[root@foundation44 mnt]# cat hello.py
#!/usr/bin/python
a=1
print a
[root@foundation44 mnt]# python hello.py 
1
[root@foundation44 mnt]# chmod +x hello.py 
[root@foundation44 mnt]# ./hello.py 
1
-----------------------------------------------




9.查看python版本
[root@foundation44 mnt]# python -V
Python 2.7.5




10.python的一些注释
(1)关于python脚本中的第一行内容 :
   #!/usr/bin/python 这种写法表示直接引用系统的默认的 Python 版本,这样的话python 程序移植到其他机器上可能运行的时候有问题,因为别人系统默认的 Python版本与你预期的并不一致。
   #!/usr/bin/env python 这种写法表示,引用环境变量里面自定义的 Python本,具有较强的可移植性,推荐这种写法。
(2)# coding:utf-8 ##有中文时加入这行才可以正确输出不报错
   格式:
        #coding:utf-8
#coding=utf-8
#encoding:utf-8
#encoding=utf-8


理解字符编码
ASCII:美国人发明了计算机,用二进制存储数据,英文字母加各个字符一共128个,每8位存储一个字符,2^8=256,可通过  ord()  函数去查看字符对应的ASCII码。
Unicode:但是ASCII码忽略了中文,韩文,日文等其他国家的文字,这个时候256个字符的对应关系明显是不够用的,这时候就用两个字节对应一个文字,2**16=65536.
UTF-8:英文字符明明可以通过一个字节存储,Unicode却需要2个字节来存储,对于存储比较小的计算机来说,是浪费很多不必要占用的空间,这个时候就出现utf-8。那么什么是utf-8呢?简单来说就是可变长度编码格式,英文字符用ASCII码来存,而中文呢,就用utf-8来存,这个时候中文就不是两个字节存储,而是三个字节来存。


而python编程有个要注意的问题,当python90年代还没有出现Unicode,使用时需要手动指定Unicode格式。# 指定存储格式为Unicode
[kiosk@foundation0 ~]$ python
Python 2.7.5 (default, Aug  2 2016, 04:20:16)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'westos'
>>> type(a)
<type 'str'>
>>> b = u'westos'
>>> type(b)
<type 'unicode'>


(3)切记:
绝对不能使用  word  (不是纯文本文件)和  windows  自带的记事本(在文件开始的地方加特殊字符  0xefbbbf<16进制>UTF-8BOM  ,有了前缀,程序自动判断它为  utf-8  格式,并按  utf-8  格式解析文本或字符串,否则,需要按照字符编码格式一个个去验证。
----------------------------------------------
有汉字报错:
[root@foundation44 mnt]# cat hello.py 
#!/usr/bin/python
a=1
print a
print "你好!"
[root@foundation44 mnt]# ./hello.py 
  File "./hello.py", line 4
SyntaxError: Non-ASCII character '\xe4' in file ./hello.py on line 4, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
更改后:
[root@foundation44 mnt]# vim hello.py 
[root@foundation44 mnt]# ./hello.py 
1
你好!
[root@foundation44 mnt]# cat hello.py 
#!/usr/bin/env python
# coding:utf-8
a=1
print a
print "你好!"
----------------------------------------------




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




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


示例:
python显示  hello world 
#!/usr/bin/env python
def hello():
    print "hello world"
 
def main():
    hello()
 
main()






13.python注释
单行注释:#常被用作单行注释符号,#开头的行,其右边的任何数据都会被忽略,当做是注释。
块注释:需批量文本或代码时,使用三引号''' ''',当然三引号也可以实现多行文本格式化打印。








14.字符的编码与解码


ASCII:  1字节=8位   2^8=256
Unicode:2字节=16位   2^16=65536  英文:2字节  中文:2字节
utf-8:  英文:1字节   中文:3字节
GB2312: 2字节


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


# 定义一变量,编码格式为unicode
>>> name_unicode = u'粉条'
>>> type(name_unicode)
<type 'unicode'>
 
# 字符的编码,从unicode到utf-8格式
>>> name_utf8 = name_unicode.encode('utf-8')
>>> type(name_utf8)
<type 'str'>
 
# 字符的解码操作,从utf-8解码到unicode编码格式
>>> name_to_unicode = name_utf8.decode('utf-8')
>>> type(name_to_unicode)
<type 'unicode'>
-----------------------------------------------
>>> name="高手"
>>> type(name)
<type 'str'>
>>> name = name.decode('utf-8')
>>> type(name)
<type 'unicode'>
>>> name = name.encode('utf-8')
>>> type(name)
<type 'str'>
>>> name = name.encode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 0: ordinal not in range(128)
>>> 
-------------------------------------------


########################
#### python 基础概念 ####
########################


1.输入与输出


输出: 告诉用户程序执行的结果
# print + 字符串...    //字符串可为多个,逗号隔开
# print + 数字|表达式
>> print 300
300
>>> print '100+200=', 100+200
100+200= 300


输入: 告诉计算机程序所需的信息
# raw_input写入的内容赋值给变量name,输入的内容为字符类型
>>> name = raw_input("Name:")
Name:westos
>>> print name
westos
>>> type(name)
<type 'str'>
 
# input写入的内容赋值给变量age,输入的内容为数值类型
>>> age = input("Age:")
Age:12
>>> type(age)
<type 'int'>
----------------------------------------
In [1]: 5/2
Out[1]: 2


In [2]: from __future__ import division


In [3]: 5/2
Out[3]: 2.5


In [4]: print '5 / 2 = %d' %(5/2)
5 / 2 = 2


In [5]: print '5 / 2 = %f' %(5/2)
5 / 2 = 2.500000


In [6]: print '5 / 2 = %.f' %(5/2)
5 / 2 = 2


In [7]: print '5 / 2 = %.1f' %(5/2)
5 / 2 = 2.5


In [8]: print '5 / 2 = %.3f' %(5/2)
5 / 2 = 2.500
------------------------------------------




2.变量
变量是内存中的一块区域。
变量的命名: 变量名由字母,数字,下划线组成。
>>> a=1
>>> print a
1
>>> a_1 = 111
>>> _a = 222
>>> print _a
222
>>> 1a = 111
  File "<stdin>", line 1
    1a = 111
     ^
SyntaxError: invalid syntax        //指语法错误,无效的语法
 
 
>>> a = 5
>>> b = 3>>> print a + b
8
>>> print a + b +c
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'c' is not defined        //名称错误
变量的特性:
实际存储在内存上;
变量名最好见名知意;
变量可重新赋值;
>>> number1 = 1
>>> number2 = 2
>>> number1 + number2
3
python中地址变量与c语言刚好相反,一条数据包含包含多个标签;
>>> a = 1
>>> b = 1
>>> id(a)
10812520
>>> id(b)
10812520




3.运算符与表达式
赋值运算符:=, +=, -=, /=, *=, %=
算术运算符:+, -, , /, //, %, *
  >>> 1 + 1
  2
  >>> 1 - 1
  0
  >>> 1 * 3
  3
  >>> 1 / 2
  0
  >>> 1.0 / 2
  0.5
  >>> 1.0 // 2
  0.0
  >>> 1 % 2
  1
  >>> 2 ** 3
  8
  >>> a33 = 3 ** 3
  >>> print a33
  27
  >>> print "a33=",a33
  a33= 27
  >>> print "a33 =",a33
  a33 = 27
关系运算符: >, >=, <, <=, !=, ==
布尔值:1 < 2,返回一个布尔类型的结果
>>> 1 < 2
True
>>> 1 > 2False
逻辑运算符:逻辑与and, 逻辑或or, 逻辑非not
练习:
编写一四则表达式,(if语句实现)




##############################
##### python的基本数据类型 #####
##############################


背景
面试题案例: 123和“123”一样么?
- 从数字角度讲
- 从程序语言的识别来讲
>>> a = 123
>>> stra = "123"
>>> a == stra
False
>>> print a
123
>>> print stra
123
>>> a + stra
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'




数字
整型>>> num1 = 123
>>> type(num1)
<type 'int'>
>>> type(123)
<type 'int'>




长整形
>>> num2 = 999999999999999
>>> type(num2)
<type 'int'>
强制定义为长整型: num3 = 123L
>>> num3 = 123L
>>> type(num3)
<type 'long'>




浮点型:表示小数
>>> f1 = 12
>>> type(f1)
<type 'int'>
>>> f2 = 12.0
>>> type(f2)
<type 'float'>




复数类型:python对复数提供内嵌支持,eg: 3.14j, 8.32e-36j
>>> c = 3.14
>>> type(c)
<type 'float'>
>>> c = 3.14j
>>> type(c)
<type 'complex'>




字符串
字符串的定义
# 字符串定义的第一种方式:
>>> str1 = 'our company is westos'
 
# 字符串定义的第二种方式:
>>> str2 = "our company is westos"
 
# 字符串定义的第三种方式:
>>> str3 = """our company is westos"""
 
>>> type(str1)
<type 'str'>
>>> type(str2)
<type 'str'>
>>> type(str3)
<type 'str'>
 
 
>>> say = 'let\'s go'>>> say
"let's go"
>>> say = "let's go "
>>> say
"let's go "




转义符号
>>> mail = "tom: hello i am westos "
>>> print mail
tom: hello i am westos
>>> mail = "tom:\n hello\n i am westos "
>>> print mail
tom:
hello
i am westos




三重引号
块注释
函数的doc文档
字符串格式化
>>> mail = """tom:
...     i am jack
...     good luck
... """
>>> print mail
tom:
    i am jack
    good luck
>>> mail
'tom:\n\ti am jack\n\tgood luck\n'字符串索引
>>> a = 'abcde'
>>> type(a)
<type 'str'>
>>> a[0]
'a'
>>> a[1]
'b'
>>> a[3]
'd'
>>> a[0]+a[1]
'ab'
>>> a[0]+a[2]
'ac'




字符串切片
>>> a
'abcde'
>>> a[1:5:2]
'bd'
>>> a[1:5]        //代表切片取出第2个到第4个
'bcde'
>>> a[:5]
'abcde'
>>> a[4:]
'e'
>>> a[4:1]            //python中默认是从左向右取值
''
>>> a[4:1:-1]        //当步长为-1时,从右向左取值
'edc'
>>> a[:]'abcde'
 
 
>>> a[-1]
'e'
>>> a[-4:-1]        //代表倒数第2个到倒数第4个切片
'bcd'
>>> a[-2:-4]
''
>>> a[-2:-4:1]
''
>>> a[-2:-4:-1]
'dc'






###############
##### 程序 #####
###############


(1)判断一个数字与10的关系
#!/usr/bin/env python
#coding=utf-8
num = int(input("please give me a number: "))
if num > 10:
    print("the num is bigger than 10!\n")
elif num == 10:
    print("the nummber is eql than 10!\n")
else:
    print("the nummber is smaller than 10!\n")


print num-10






(2)编写一程序,录入信息包括  hostname、IP、used_year、CPU、Memory、manager_name  ,如果使用年限超过10年,直接显示警告
信息“该服务器使用年限太久!”,如果使用年限不超过10年,显示该服务器信息如下面的格式如下:
主机信息
主机名: hostname
IP:IP
使用年限:used_year
CPU:CPU
Memory:Memory
------------------------------------------------
#!/usr/bin/env python
# coding=utf-8
hostname = raw_input("Hostname: ")
IP = raw_input("ip: ")
used_year = input("usedyear: ")
CPU = raw_input("cpu: ")
Memory = raw_input("memory: ")
manage_name = raw_input("managename: ")


if used_year > 10:
    print ("该服务器使用年限过久!!\n")
else:
    print '主机名:'+str(hostname)
    print 'IP:'+str(IP)
    print '使用年限:'+repr(used_year)
    print 'CPU:'+str(CPU)
    print 'Memory:'+str(manage_name)


~~~~~~
/usr/bin/python2.7 /home/kiosk/PycharmProjects/untitled/hello.py
Hostname: yy
ip: 172.25.254.137
usedyear: 5
cpu: i5
memory: 4G
managename: qq
主机名:yy
IP:172.25.254.137
使用年限:5
CPU:i5
Memory:qq










(3)编写一四则表达式,(if语句实现)


#!/usr/bin/env python
# coding=utf-8
x=input()
m=raw_input()
y=input()


if m=='+':
    print x+y
elif m=='-':
    print x-y
elif m=='*':
    print x*y
elif m=='/':
    print x / y
else:
    print 'ERROR!!'


~~~~~~~~~
/usr/bin/python2.7 /home/kiosk/PycharmProjects/untitled/hello.py
3
/
2
1


Process finished with exit code 0








(4)创建一个python脚本,实现以下功能
要求用户输入用户和密码;
如果用户名&密码均正确,显示“welcome to user manage ststem”;
如果不正确,重新输入,最多3次机会
输入超过3次,报错“你已经登录过3次,请于10min后再登录”。


#!/usr/bin/env python
# coding=utf-8
user='yy'
passwd='123'
i=3


while i>0:
    name = raw_input("please give me an username: ")
    password = raw_input("please give me the user's password: ")
    if (name == user) and (password == passwd):
        break
    i=i-1


if i>0:
    print 'welcome to use manage system!'
else:
    print '你已经登陆过三次,请10min后再登陆'


~~~~~~~~~~~~


test:
<1>
/usr/bin/python2.7 /home/kiosk/PycharmProjects/yy/hello.py
please give me an username: yy
please give me the user's password: 123
welcome to use manage system!


Process finished with exit code 0
<2>
/usr/bin/python2.7 /home/kiosk/PycharmProjects/yy/hello.py
please give me an username: yu
please give me the user's password: 123
please give me an username: yy
please give me the user's password: 123
welcome to use manage system!


Process finished with exit code 0
<3>
/usr/bin/python2.7 /home/kiosk/PycharmProjects/yy/hello.py
please give me an username: yu
please give me the user's password: 123
please give me an username: ui
please give me the user's password: 334
please give me an username: ui
please give me the user's password: 44
你已经登陆过三次,请10min后再登陆


Process finished with exit code 0





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值