python午后茶(一)



写在前面的话:

通过花费15分钟(上个大号绰绰有余吧)的时间,新手对python会有一个大概的印象吧。 这篇文章是模仿陈皓大牛的一篇文章的格局写的:http://coolshell.cn/articles/10739.html.或者自行搜索:lua site:coolshell.cn

python位列3P(perl,php,python)之一。业界这样定义它:1)脚本语言:2)胶水语言:

阅读了之后,留下这篇文章做个备忘录,

这本99页的小册子描述的是老版本的python2.3,我的ubuntu自带python2.7.6


且放白鹿青牙间:

1)tips:

python声明变量是动态的,a=1,a='hhh'完全是运行后才知道变量的类型 ubuntu下输入python进入python模式,输入exit()退回到ubuntu. 1)print语句自动换行,如果你加了'\n',那么程序就会连换两行. 2)输出变量,采用%表明变量. 3)井号单行注释:#print('so i cannot print this line') 三个单引号或者三个双引号多行注释:'''print('so i cannot print these lines')''' 4)运行环境:在windows下,安装python,打开python.exe,就可以运行命令了,E:\python\Doc\ 这里面还有ptyhon手册。 在linux下,自带python的说,我是换源之后,系统更新就有了ptyhon2.7(关于换源,可以google: 换源 site:oschina.net) 5)涉及路径名的时候,如果出现中文字符,可能会遇到乱码情况。(事实上,我还是遇到中文问题,所以我决定不用中文)解决如下: 在代码第一行加入:# This Python file uses the following encoding: utf-8 1.1 打印
a='hello world'
print'hello world'    python3.x不支持老版本
print('hello world')    新版本
print(a)     
          | |hello world
python就像string类一样,自动执行+=操作,join操作为括号里的每个字符执行一个+=操作
print('hhh',a,'hhh')
print('hhh',a,'aaa'.join('hhh'))
       ||hhh hello world hhh
       ||hhh hello world haaahaaah

注意下面的逗号和百分号
print('what is a:',a)
print('print twice a :%s,%s' %(a,a))
       | |what is a: hello world
       | |print twice a :hello world,hello world
1.2 数据类型: 1.2.1数字类型:int , long int, float(2.3e-3==2.3*0.001), complex(复数:-5+4j) 1.2.2字符串: 单引号:a='hello world' | | hello world 双引号: a=''hello world'' | | hello world 三个单引号:a='''hello world''' 1.3 操作符: >>>2*3 | |6

2)控制语句 :

每一次语句后面都要加冒号:。句末不用分号也可以。 顺序。 选择:if A: elif B: else: 循环:while True: do sth break 这里的loop循环中的range,只能用于整形
>>> for i in range(1,5):
    print(i)
else:
    print('loop over')

    
1
2
3
4
loop over
usrName=['allen','allen2'] #这是一个List数据结构
while True:
    s=input('please enter your name :')
    for checkName in usrName:
        if s==checkName:
            print('weclome:%s' %s)
            break
        elif s=='root':
            print('weclime:',s)
            break
    s2=input('enter q to quit:')
    if s2=='q':
        print('get away!~!')
        break
如果要一探究竟,可以自己练习一遍。

3)函数和模块:

函数之无参数函数
def syHi():
    print('i am allen.lidh')
syHi()


>>> 
i am allen.lidh
函数之缺省值参数:缺省参数的右边的参数必须全部都有缺省值。(编译器从左至右匹配参数,只有在被传递的参数匹配完毕后, 编译器才会去看变量是不是有缺省值)
def syHi(a=1,b,c)
#这样定义是错的

def syHi(a,b=4,c=5):
    print('a:',a,'b:',b,'c:',c)
syHi(1,2)


>>> 
a: 1 b: 2 c: 5
参数之局部和全局变量
def syHi(x):
    x=3
    global y
    y=22

    
x=7
y=77
syHi(x)
print('x:',x,'y:',y)
输出: >>> x: 7 y: 22

模块之间的调用: 1)import pyFile,不能引用数字开头的文件名。import 01这是错误的。import one will be nice 首先在two.py中有如下: #two.py def sayhi(): print('i am from two.py') version=0.2 我么再在1.py中作模块之间的调用.
模块之import pyFile
import two
two.sayhi()
print(two.version)

>>> 
i am from two.py
0.2
    
模块之from pyFile import var1,func1
from two import sayhi,version
sayhi()
print(version)

>>> 
i am from two.py
0.2

4)数据结构:

------------------------------------------------------------------------------------------------------------ List(链表。中文翻译没意思,图个好理解)| Tuple(数组) | Dictionary(字典:键值对) 链表比较随意,元素可以删增也可以赋值,但数组不可以:immutable like string. ------------------------------------------------------------------------------------------------------------ List:
>>> myList=['item1','item2']
>>> myList.append('item3')
>>> print('length:',len(myList),'list[0]:',myList[0])
('length:', 3, 'list[0]:', 'item1')
>>> del myList[0]
>>> myList.sort()
>>> for i in myList:print i
... 
item2
item3
Tuple:
>>> myTuple=('item1','item2')
>>> yourTuple=('item3',myTuple)
>>> print(yourTuple[1][0])
item1
DIctionary:
>>> myDic={'happy':'laughing',
...                'sad':'laughed'}
>>> #add a key-value item
... myDic['sb']='no-brain'
>>> del myDic['sad']
>>> for me,you in myDic.items():
...        print('me:',me,' while you ',you)
... 
('me:', 'sb', ' while you ', 'no-brain')
('me:', 'happy', ' while you ', 'laughing')
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
注意:如果要进一步了解这些数据结构,在ubuntu下输入python,然后输入help(tuple),超详细。 \
以tuple为例:
>>> a=tuple()
>>> a
()
>>> a=tuple('hahah')
>>> a
('h', 'a', 'h', 'a', 'h')
>>> b=a+a
>>> b
('h', 'a', 'h', 'a', 'h', 'h', 'a', 'h', 'a', 'h')
>>> for i in a: print i
... 
h
a
h
a
h
>>> b==a
False
>>> b>=a
True
>>> 
--------------------------------------------------------------------------------------------------------------------------------------------------------

5)写脚本

在大家都说不清楚的大数据时代和云计算时代,做linux运维应该蛮好的,事实上,我也想这样。写脚本应该是运维工作的基础的。 下面这个脚本,将/home/allen-li/hhh.gif' 文件名改成 '/home/allen-li/allen_lidh.gif'
import os
source='/home/allen-li/'
fileName=raw_input('enter the file you want to operate on:')
#这里其实应该有个检测文件名合法性的操作

src_file=source+fileName+'.gif'
des_file=source+'allen_lidh'+'.gif'
myCommand="mv '%s' '%s' " %(src_file,des_file)      #unix命令行
print(myCommand)
if os.system(myCommand)==0:
	print'return True'
else:
	print 'return False'
输出:输出的结果就是这张gif的名字发生改变
allen-li@allenli-U80V:~$ python /home/allen-li/mypy1.py
enter the file you want to operate on:hhh
mv '/home/allen-li/hhh.gif' '/home/allen-li/allen_lidh.gif' 
return True
这张gif让我笑到爆,不过图片太大传不了,只好截图吧 \

6)面向对象:继承

注意点: __init()__就是完成类的初始化工作,类似于C++的构造函数 self可以推之以C++的this的指针 class A(B):表示A继承于B
class Person:
	def __init__(self,name,sex):
		self.name=name
		self.sex=sex
	def syHi(self):
		print ("name:'%s' sex:'%s'" %(self.name,self.sex));
class Student(Person):
	def __init__(self,name,sex,sid):
		Person.__init__(self,name,sex)
		self.sid=sid
	def syHi(self):
		Person.syHi(self)
		print("sid:'%s'" %self.sid)
class Teacher(Person):
	def __init__(self,name,sex,tid):
		Person.__init__(self,name,sex)
		self.tid=tid
	def syHi(self):
		Person.syHi(self)
		print("tid:'%s' " %self.tid)

s=Student('allen.lidh2','boy2',100)
t=Teacher('allen.lidh3','boy3',100100)
s.syHi()
t.syHi();
输出:
allen-li@allenli-U80V:~$ python /home/allen-li/桌面/mypy1.py
name:'allen.lidh2' sex:'boy2'
sid:'100'
name:'allen.lidh3' sex:'boy3'
tid:'100100' 

7)文件操作与异常

import time
try:
	f=file('/home/allen-li/桌面/allen.lidh.txt','wb+')    #这里的file和下面的open有什么区别?
	s="hello i am allen.lidh \n in shu"
        #	f.write(bytes(s,"utf-8"))     #这是python 3.X的写法
        f.write(s)                            #写和读不能同时进行,学过os就应该知道这是缓冲区没有及时刷新
        f=open('/home/allen-li/桌面/allen.lidh.txt','wb+')
	while True:
		#line=f.readline()
		line=f.read(16)               #16个字节读一次
		if len(line)==0:
			break
		print(line)	
finally:
	
	f.close()
	print('bye:%s' %time.strftime('%Y-%m-%d-%H-%M'))    #时间函数

>>>
allen-li@allenli-U80V:~$ python /home/allen-li/桌面/mypy1.py
hello i am allen
.lidh 
 in shu
bye:2014-04-30-00-42


8)类裤:

隔壁的同学买了一本关于python library超厚的书,我不禁缩了。。。

作为弥补,贴了Lambda的例子吧,C++11把这个特性列为标准了。

def makeTwice(n):
	return lambda s:s*n
twice=makeTwice(2)

print(twice(7))
print(twice('hhh'))

>>>
allen-li@allenli-U80V:~$ python /home/allen-li/桌面/mypy1.py
14
hhhhhh
#感觉这个跟正则一样走的非主流,


写在后面的话:

写博客真的耗时间,所以说懂得抓主干会让你多活20年,显然这篇博客跟shi一样杂乱无章且水。 感觉语言一通百通,因为他们提供给我么的功能大同小异。在繁杂的语言中,懂得抽象则清风自来,尽情盛开。
学习python的一点资料: a byte of python 外文网址一
w3school




相关内容

    暂无相关文章

评论关闭